问题描述
我有一个具有以下关联的表格:
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
我想做的是允许想要添加新Course
的人从所选类别中选择所有技能,并能够使用复选框来添加它们.在视图中,我这样做是这样的:
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:
查看
<%= 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?
谢谢.
推荐答案
在 Rails 4 中,现在有一个很棒的 collection_check_boxes
表单帮助方法.
In Rails 4 there's now an awesome collection_check_boxes
form helper method.
从 Rails API文档 :
<%= 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 %>
关于collection_check_boxes
的最酷的事情是可以选择[花一个方块]( http://api.rubyonrails.org/classes/ActionView /Helpers/FormOptionsHelper.html#method-i-collection_check_boxes ),您可以自定义生成的标记(例如,用于样式设置):
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
这篇关于如何在Rails 4中以一种形式添加多个多对多字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!