开发者

How to associate an id from a select form with another object?

开发者 https://www.devze.com 2023-02-19 19:05 出处:网络
I have two models: Study and StudyType. The later has just two columns: id and name and stores the type of a study like Bachelor, Master and so on. All values are inserted already. I used the command

I have two models: Study and StudyType. The later has just two columns: id and name and stores the type of a study like Bachelor, Master and so on. All values are inserted already. I used the command rake db:seed after add the appropriate statements to /db/seeds.rb.

The StudyType has_many :studies where as the Study belongs_to :study_type and accepts_nested_attributes_for :study_type.

Now I want a select field in my new-study-form. I created the select field (see below) but when I submit the form the form inserts a new entry in the study_types table?!? instead of setting the id of the study_type in the study object. Can you help me?

Here is the new action of the studies_controller

@study = Study.new
...
@study.study_type = StudyType.new

Here is the study partial:

<%= render :partial => "shared/study_form_fields", :locals => { :study_fields => study_fields } %>  
...
<%= study_fields.fields_for :subject_type do |st开发者_如何学Goudy_type_fields| %>
  <%= render :partial => "shared/study_type_form_fields", :locals => { :study_type_fields => study_type_fields } %>
<% end %><!-- End of study_type_fields -->
...

Here is the study_type partial.

# 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." %>


I should you need to use study_type_id instead of name here

# 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." %>
0

精彩评论

暂无评论...
验证码 换一张
取 消