【发布时间】:2011-10-26 21:09:50
【问题描述】:
我正在尝试使用 has-many through 关联来实现 Rails3 嵌套表单。
我的模型关系如下(我的模型是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 上使用带有 Ruby 1.8.7 的 Rails 3。
【问题讨论】:
标签: ruby-on-rails-3 activerecord nested-forms has-many-through