How to add multiple many-to-many fields in one form with Rails 4?

折月煮酒 提交于 2019-12-21 23:09:09

问题


I have a form that's got the following association:

Course.rb

has_and_belongs_to_many :skills

Skill.rb

has_and_belongs_to_many :courses

what I wanna do is allow the person who wants to add a new Course select all the skills from his selected category and be able to add them by using a checkbox. In the view I've done like so:

VIEW

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

Sadly this isn't working and I get the following error:

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

could you please help on finding a fix for my issue?

Thank you.


回答1:


In Rails 4 there's now an awesome collection_check_boxes form helper method.

From the Rails API docs:

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

In your setting, it might be something like this:

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

The cool thing about collection_check_boxes is that is optionally [takes a block]( http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_check_boxes) which let's you customize the generated markup (e.g. for styling purposes):

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



回答2:


I think you should use this code:

For Rails 3.*

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

For Rails 4.* As mentioned in comment, Rails 4 introduced collection_check_boxes, so your code may look like:

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

See documentation for check_box_tag: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-check_box_tag

How to handle HABTM in Rails I recommend this Railscast, or the code is available here.



来源:https://stackoverflow.com/questions/23814740/how-to-add-multiple-many-to-many-fields-in-one-form-with-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!