2014-05-22 75 views
2

我有那種有下列關聯的一種形式:如何用Rails 4在一個表單中添加多個多對多字段?

Course.rb

has_and_belongs_to_many :skills 

Skill.rb

has_and_belongs_to_many :courses 

做的是我想做的允許誰想要的人要添加新的Course,請從他所選的類別中選擇所有技能,並使用複選框添加它們。在視圖我已經做了,像這樣:

VIEW

<%= form_for(@course) do |f| %> 
    <% @skills.each do |s| %> 
    <%= f.check_box :value => s.id %> <%= s.title %><br /> 
    <% end %> 
<% end %> 

可悲的是,這是不工作,我得到以下錯誤:

undefined method `{:value=>9}' for #<Course:0x00000004ce0208> 

請你在尋找幫助解決我的問題?

謝謝。

+1

嘗試給它像這樣''%= check_box_tag「course [skill_ids] []」,s.id,current_skill_ids.include?(s.id)%>' – Pavan

+0

在做這些之前, %current_skill_ids = @ course.skill_ids%>'。 – Pavan

+0

這表明他們沒事,謝謝。但是他們沒有被保存在'courses_skills'表中,你有什麼想法可以阻止他們呢? – Xeen

回答

3

Rails 4現在有一個很棒的collection_check_boxes窗體幫助方法。

Rails API docs

<%= form_for @post do |f| %> 
    <%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %> 
    <%= f.submit %> 
<% end %> 

在你的設置,它可能是這樣的:

<%= form_for @course do |f| %> 
    <%= f.collection_check_boxes :skill_ids, Skill.all, :id, :name %> 
    <%= f.submit %> 
<% end %> 

很酷的事情有關collection_check_boxes是可選[花費塊( http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_check_boxes )讓您自定義生成的標記(例如,用於造型目的):

collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b| 
    b.label(:"data-value" => b.value) { b.check_box + b.text } 
end 
1

我認爲你應該使用此代碼:

對於Rails的3 *

<%= check_box_tag "course[skill_ids][]", s.id, s.title %> 

對於Rails的4 * 正如評論所說,軌道4,5介紹collection_check_boxes,使您的代碼可能看起來像:

<%= collection_check_boxes(:course, :skill_ids, Skills.all, :id, :title) %> 

請參閱文檔check_box_tag:http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag

如何處理Rails中的HABTM我推薦這個Railscast,或者代碼可用here

+1

這是在Rails 3中手動構建集合複選框的好方法。在Rails 4中,一個新的['collection_check_boxes'](http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#methodi-i -collection_check_boxes)表單助手已經被引入,完成這件事情。想想你可能會喜歡:) –

+0

我不知道!謝謝你讓我知道!那很棒。 –

相關問題