2010-01-31 2 views
2

많은 사용자 (드라이버)가있는 Journey 모델이 있습니다. accepts_nested_attributes_for를 사용하여 여행에서 드라이버를 추가 및 제거 할 수 있습니다. 드라이버를 추가 할 때 사용자에게 <을 표시하려면 >을 선택하십시오. 여기서 사용자 중 하나를 선택하여 해당 특정 여행에 속한 드라이버 중 하나가 될 수 있습니다. 그 긴왔다 :accepts_nested_attributes_for 및 collection_select보기 작성 방법

# Models 
class Journey < ActiveRecord::Base 
    has_many :drivers 
    accepts_nested_attributes_for :drivers, :allow_destroy => true 
    has_many :users, :through => :drivers 
    accepts_nested_attributes_for :users 
end 

class Driver < ActiveRecord::Base 
    belongs_to :journey 
    belongs_to :user 
end 

class User < ActiveRecord::Base 
    has_many :drivers 
    has_many :journeys, :through => :drivers 
end 

# View _form.html.erb 
<% form_for(@journey) do |f| %> 
    <%= f.error_messages %> 
    <% f.fields_for :drivers do |d| %> 
    <%= render :partial => 'driver', :locals => { :f => d } %> 
    <% end %> 
    <p><%= f.submit 'Submit' %></p> 
<% end %> 

# View _driver.html.erb 
<p><%= f.collection_select(:id, User.all, :id, :name)%></p> 

오류는 말한다 :

ActiveRecord::AssociationTypeMismatch in JourneysController#create 
Driver(#2185315860) expected, got Array(#2151950220) 

내가 내 _driver.html.erb이 잘못된 것으로 의심,하지만 난 그것을 해결하는 방법을 모른다. 너 여기 좀 힌트와 함께 좀 도와 줄래?

답변

3

귀하의 _driver.html.erb 다음과 같아야합니다

<%= f.collection_select(:user_id, User.all, :id, :name) %> 

하지만이 오류가 발생하는 경우 잘 모르겠어요. 내가 중첩 된 모델 accepts_nested_attributes_for를 사용할 때

또한, 나는이 방법을 수행

# Models 
class Journey < ActiveRecord::Base 
    has_many :drivers 
    accepts_nested_attributes_for :drivers, :allow_destroy => true 
    has_many :users, :through => :drivers 
end 

class Driver < ActiveRecord::Base 
    belongs_to :journey 
    belongs_to :user 
    accepts_nested_attributes_for :users 
end 

그래서이 같은 형태를 가질 수 있습니다

<% form_for @journey do |f| %> 
    <% fields_for :drivers do |d| %> 
     <% fields_for :user do |u| %> 
     <%= u.text_field :name %> 
     ... 
     <% end %> 
    <% end %> 
<% end %> 
+0

감사합니다! 그게 문제 였고 지금은 고정되어 있습니다 :) – Jeena

관련 문제