我正在尝试使用has-many通过关联实现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_id
表的project_fees
字段中。
我在Linux上使用Rails 3和Ruby 1.8.7。
答案 0 :(得分:0)
假设你的MySQL输出被剪切和粘贴,你可能在某个地方迁移了一个拼写错误。专栏
projec_id
project_fees
表中的应为
project_id
答案 1 :(得分:0)