2013-04-23 3 views
1

nested_form gem을 사용하여 체인 및 그 위치의 목록을 보여주는 드롭 다운을 만들려고합니다. 사용자가 제출 버튼을 클릭하면 nested_form은 users_locations라는 조이너 테이블에 새 항목을 만들어야합니다. 그러나 다음과 같이 형태가 오류를 뱉어 : 즉레일 : nested_form_for <column>은 비워 둘 수 없습니다.

User locations user can't be blank 

을, 그는 USER_ID가 NULL 불평하고 USER_ID가 user_locations 테이블에 필수이기 때문에 따라서는 (테이블에 항목을 만들 수 없습니다).

belongs_to :chain 
has_many :user_locations 
has_many :locations, :through => :user_locations 
... 
accepts_nested_attributes_for :user_locations, :reject_if => :all_blank, :allow_destroy => true 
validates_associated :user_locations, :message => ": you have duplicate entries." 
... 
attr_accessible :first_name, :last_name, ... , :user_locations_attributes 

users_controller.rb

def create 
    @user = User.new(params[:user]) 
    @user.save ? (redirect_to users_path, notice: 'User was successfully created.') : (render action: "new") 
    end 

로그인

<div class="field" id="location_toggle"> 
    <%= f.label "Location:", :class => "form_labels", required: true %> 
    <%= f.fields_for :user_locations do |location| %> 
     <%= location.grouped_collection_select :location_id, Chain.all, :locations, :name, :id, :name, include_blank: false %> 
    <% end %> 
    <%= f.link_to_add "Add a Location", :user_locations, :class => "btn btn-primary btn-small" %> 
    <br/> 
    </div> 

user.rb (모델) (사용자보기 폴더에서)

_form.html.erb 보여줍니다 :

SELECT 1 AS one FROM "user_locations" WHERE ("user_locations"."user_id" IS NULL AND "user_locations"."location_id" = 1) 
+0

@ 사용자)'블록? – charleyc

+0

예! 그것은 <% = simple_nested_form_for (@user) 안에 존재합니다. do | f | %> – Rahul

답변

2

나는 당신이 user_locationvalidates :user_id, presence: true 또는 뭔가라고 가정합니다.

최근에 this question에 대한 응답으로이 모양을 보았습니다. 중첩 모델을 만들 때 생성 될 모든 개체에 대한 유효성 검사가 실행되기 전에 실행되므로 모델에 user_id이 저장되면 설정되었을 때 유효성 검사를 할 수 없습니다.

이 해결하기 위해 당신과 함께 예를 들어, 창조에 대한 유효성 검사를 비활성화 할 수 있습니다 : 당신의`_form.html.erb``form_for의 내부에 살고 (모든 코드를 가정

# user_locations.rb 
validates :user_id, presence: true, on: :update 
+0

유효성 확인의 측면에서 정확하며이 솔루션이 효과가 있습니다. 그러나, 생성시 user_id가 있는지 확인할 수 없다는 것은 유감입니다. – Rahul

0

simple_form을 기본 Rails 양식 도우미와 혼합하여 이상한 행동을하는 것처럼 보입니다. simple_form으로 작업하지는 않았지만 f.fields_forf.simple_fields_for으로 변경하여 문제를 해결할 수 있습니다.

여기에 example이 도움이 될 수 있습니다.

+0

f.simple_fields_for로 전환했지만 여전히 작동하지 않았습니다. 그래도 제안에 감사드립니다! – Rahul

관련 문제