views:

180

answers:

1

Hi, I need some help.

I have a model Journey which has many Users (drivers). I want to be able with help of accepts_nested_attributes_for to add and remove drivers from a journey. When I add a driver I want to show the user a <select> where she can select one of the users to be one of the drivers belonging to that particular journey. I have come that long:

# 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>

The error says:

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

I suspect that my _driver.html.erb is wrong, but I have no idea how to fix it. Could you please help me out with some hints here?

+1  A: 

Your _driver.html.erb should look like this:

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

But I'm not sure if this causes the error.

Also when I use accepts_nested_attributes_for for nested models, I do it this way:

# 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

So you can have forms like this:

<% form_for @journey do |f| %>
   <% fields_for :drivers do |d| %>
      <% fields_for :user do |u| %>
        <%= u.text_field :name %>
        ...
      <% end %>
    <% end %>
<% end %>
klew
Thanks! That was the problem, and now it is fixed :)
Jeena