I’m trying to implement a Rails3 nested form with has-many through association.
My model relationships are as follows (My models are Project ProjectDuration, ProjectFee). Project can have many project duration through project_fees.
Following are my models/table
mysql> desc projects;
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(255) | YES | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
class Project < ActiveRecord::Base
has_many :project_durations, :through => :project_fees
has_many :project_fees
accepts_nested_attributes_for :project_fees
end
mysql> desc project_durations;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| duration | varchar(255) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
class ProjectDuration < ActiveRecord::Base
has_many :projects, :through => :project_fees
has_many :project_fees
end
mysql> desc project_fees;
+---------------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| projec_id | int(11) | YES | | NULL | |
| project_duration_id | int(11) | YES | | NULL | |
| fee | float | YES | | NULL | |
+---------------------+----------+------+-----+---------+----------------+
class ProjectFee < ActiveRecord::Base
belongs_to :projects
belongs_to :project_durations
end
And my projects_controllers new action is as follows
class ProjectsController < AdminsController
def new
@project = Project.new
@project_durations = ProjectDuration.find(:all)
project_fees = @project.project_fees.build()
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @project }
end
end
end
And I finally I have the following view (new.erb)
<%= form_for(@project, :html => { :class => :form }) do |f| -%>
<% @project_durations.each do |duration| %>
<%= f.fields_for :project_fees do |builder| %>
<%= render 'fee_fields', :f => builder, :project => @project, :duration => duration %>
<% end %>
<% end %>
<% end -%>
and ‘fee_fields’ is as
<ul>
<li>
<%= duration.duration %>
<%= f.text_field :fee %>
<%= f.hidden_field :project_duration_id, :value => duration.id %>
</li>
</ul>
Even though this saves data to ‘project_fees’ table, it does not save data in the project_id field of the project_fees table.
I’m using Rails 3 with Ruby 1.8.7 on Linux.
This was the life saver for me
http://iqbalfarabi.net/2011/01/20/rails-nested-form-with-has-many-through-association/