I’m trying to implement a has_many :through join in Rails 3 (with Formtastic) and I’m a little stuck. I have the models set up as follows:
Models:
class Project < ActiveRecord::Base
has_many :employees, :through => :teams
has_many :teams
class Employee < ActiveRecord::Base
has_many :projects, :through => :teams
has_many :teams
class Team < ActiveRecord::Base
belongs_to :project
belongs_to :employee
And this line gives me a multi-select box in the projects view that allows employees to be selected:
View:
<%= f.input :employees, :as => :select %>
So far this gets the job done, but what I’d LIKE to have is a separate dropdown box to select each employee’s name, then their role in the project. I can’t figure out the form code to get me there…
EDIT:
As suggested, I’ve gotten the code from Railscast 197: Nested Model Forms working and it’s part-way there. This is what I have in the view:
<%= f.semantic_fields_for :employees do |builder| %>
<%= render 'employee_fields', :f => builder %>
<% end %>
<%= link_to_add_fields "add employee", f, :employees %>
and the ’employee_fields’ partial:
<p class="fields">
<%= f.input :name, :as => :select, :collection => Employee.find(:all) %>
<%= f.hidden_field :_destroy %>
<%= link_to_remove_fields "remove", f %>
</p>
But right now this creates a new employee rather than a new team (project-employee join record), so I think it’s acting as a has_many rather than a has_many :through. How can I edit this so that the :name input above adds a record to project[employee_ids][]?
Oh my god, I finally got this thing to work. Here’s the relevant code, minus the bits added to make the form add and remove fields dynamically:
_form.html.erb
_team_fields.html.erb
The key was adding the
<input id="project_teams_none" name="team[employee_ids][]" type="hidden" value="" />line in manually, because for whatever reason this wasn’t generated as part of the form. This got the form to actually start updating things, and then I just had to make the nested form refer to the join model (team) rather than toemployeesso that the updates were going to the right place.Looks so simple now!