views:

163

answers:

1

I'm building a form for a :has_many :through relationship:

class Account < ActiveRecord::Base
  has_many :employments
  has_many :people, :through => :employments
  accepts_nested_attributes_for :employments
end

class Person < ActiveRecord::Base
  has_many :employments
  has_many :accounts, :through => :employments
end

class Employment < ActiveRecord::Base
  belongs_to :account
  belongs_to :person
end

The Employment model contains the fields :account_id and :person_id.

Within the account form, I'm adding:

<% fields_for 'account[employments_attributes][]', @account.employments do |e| %>
  <%= e.hidden_field :account_id, :value => @account.id %>
  <%= e.collection_select :person_id, Person.all, :id, :name %>
<% end %>

collection_select, or select as well, in any permutation I give them fail with a NoMethodError exception:

undefined method `person_id' for #<Array:0x82e7db0>

It's as if the person_id field doesn't exist and yet I can call the create method with :account_id and :person_id perfectly fine.

+1  A: 

Answering my own question. As I'm training my brain to think the Rails way, I've been running into situations like these where I'm simply thinking about the problem wrong.

forms_for needs to act on an already-instantiated object from the controller. Rather than this being a form to create the employment object, it's filling in the fields in an empty one. So, I needed to create an empty employment object in the edit action:

@account.employments.build

encapsulated with the proper logic so it only gets created when I need it.

Adam Lassek