【问题标题】:How to associate an id from a select form with another object?如何将选择表单中的 id 与另一个对象相关联?
【发布时间】:2011-03-26 19:21:46
【问题描述】:

我有两个模型:StudyStudyType。后者只有两列:idname,并存储像 BachelorMaster 等学习类型。所有值都已插入。在将适当的语句添加到/db/seeds.rb 之后,我使用了命令rake db:seed
StudyType has_many :studies 其中 Study belongs_to :study_typeaccepts_nested_attributes_for :study_type

现在我想在我的新学习表格中添加一个选择字段。我创建了选择字段(见下文),但是当我提交表单时,表单study_types 表中插入一个新条目?!?而不是在study 对象中设置study_typeid。你能帮帮我吗?

这是studies_controllernew 操作

@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


    【解决方案1】:

    我应该在这里使用study_type_id 而不是name

    # File: _study_type_form_fields.html.erb
    <%= study_type_fields.label :study_type_id, "Study type" %>
    <%= study_type_fields.collection_select :study_type_id, StudyType.all, :id, :name, :prompt => "Please select a study type." %>
    

    【讨论】:

      猜你喜欢
      • 2019-03-21
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多