【发布时间】:2011-03-26 19:21:46
【问题描述】:
我有两个模型:Study 和 StudyType。后者只有两列:id 和 name,并存储像 Bachelor、Master 等学习类型。所有值都已插入。在将适当的语句添加到/db/seeds.rb 之后,我使用了命令rake db:seed。StudyType has_many :studies 其中 Study belongs_to :study_type 和 accepts_nested_attributes_for :study_type。
现在我想在我的新学习表格中添加一个选择字段。我创建了选择字段(见下文),但是当我提交表单时,表单在study_types 表中插入一个新条目?!?而不是在study 对象中设置study_type 的id。你能帮帮我吗?
这是studies_controller 的new 操作
@study = Study.new
...
@study.study_type = StudyType.new
这是研究的部分内容:
<%= render :partial => "shared/study_form_fields", :locals => { :study_fields => study_fields } %>
...
<%= study_fields.fields_for :subject_type do |study_type_fields| %>
<%= render :partial => "shared/study_type_form_fields", :locals => { :study_type_fields => study_type_fields } %>
<% end %><!-- End of study_type_fields -->
...
这里是 study_type 部分。
# File: _study_type_form_fields.html.erb
<%= study_type_fields.label :name, "Study type" %>
<%= study_type_fields.collection_select :name, StudyType.all, :id, :name, :prompt => "Please select a study type." %>
【问题讨论】:
标签: ruby-on-rails select associations nested-forms form-helpers