我有一个模型Journey,有很多用户(驱动程序)。我希望能够在accepts_nested_attributes_for的帮助下添加和删除旅程中的驱动程序。当我添加驱动程序时,我想向用户显示< 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错了,但我不知道如何修复它。你能帮我解决一些提示吗?
答案 0 :(得分: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 %>