使用 Rails 4 的 HABTM 关系的多选问题 [英] Multiple select issue with a HABTM relationship using Rails 4
本文介绍了使用 Rails 4 的 HABTM 关系的多选问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
虽然代码似乎是正确的,但当我尝试发送表单时,没有发送多选的值.
Although the code seems to be right, when I try to send the form, the values of the multiple select aren't being sent.
如果我只是删除多个选项,那么考虑到一个值,一切都按预期工作,但重要的是要为每个事务存储一个以上的标签.
If I just remove the multiple option, everything works as expected considering just one value, but it's important to store more than one tag per transaction.
模型
Transaction.rb
class Transaction < ActiveRecord::Base
has_and_belongs_to_many :tags
Tag.rb
class tag < ActiveRecord::Base
has_and_belongs_to_many :transactions
查看
<%= form.collection_select :tag_ids, @tags, :id, :name, {},
{:multiple => true} %>
结果:
<select id="transaction_tag_ids" multiple="multiple" name="transaction[tag_ids][]">
<option value="1">..</option>
</select>
推荐答案
确保您正确允许接收的参数用于批量分配.
Be sure what you properly allow received params for mass assignment.
你说 one param 有效,所以我假设你在控制器的某个地方有这样的东西:
You said that the one param works, so I assume what you have somewhere in your controller something like:
params.require(:transaction).permit(:name, :tag_ids)
所以你需要允许接收一个数组:
So you need allow to receive an array:
params.require(:transaction).permit(:name, :tag_ids => [])
这篇关于使用 Rails 4 的 HABTM 关系的多选问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文