我试图通过关联实现Rails3与has-many的嵌套表单。通过关联实现Rails 3与has-many的嵌套表单
我的模型关系如下(我的模型是Project ProjectDuration,ProjectFee)。通过project_fees项目可以有很多项目持续时间。
以下是我的模型/表
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
而且我projects_controllers新的操作如下
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
我终于我有以下几点看法(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 -%>
和'fee_fields'为
<ul>
<li>
<%= duration.duration %>
<%= f.text_field :fee %>
<%= f.hidden_field :project_duration_id, :value => duration.id %>
</li>
</ul>
即使这个数据保存到“project_fees”表,它不会在project_fees
表的project_id
现场保存数据。
我在Linux上使用Rails 3和Ruby 1.8.7。