使用Rails 4与HABTM关系的多选问题4 [英] Multiple select issue with a HABTM relationship using Rails 4

查看:149
本文介绍了使用Rails 4与HABTM关系的多选问题4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管代码似乎是正确的,但当我尝试发送表单时,多重选择的值并未发送。



如果我只是删除多重选项,一切都按预期工作,只考虑一个值,但每个交易存储一个以上的代码非常重要。

p>

Transaction.rb

  class Transaction< ; ActiveRecord :: Base 
has_and_belongs_to_many:tags

Tag.rb

  class tag< ActiveRecord :: Base 
has_and_belongs_to_many:交易

查看

 <%= form.collection_select:tag_ids,@tags,:id,:name,{},
{多个=> true}%>

结果:

 < select id =transaction_tag_idsmultiple =multiplename =transaction [tag_ids] []> 
< option value =1> ..< / option>
< / select>


解决方案

确保您正确允许接收的参数用于质量分配。



你说这个参数有效,所以我假设你在你的控制器中有什么地方:

  params.require(:transaction).permit(:name,:tag_ids)

所以你需要允许接收一个数组:

  params.require(:transaction).permit(: name,:tag_ids => [])


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.

Model

Transaction.rb

class Transaction < ActiveRecord::Base
    has_and_belongs_to_many :tags

Tag.rb

class tag < ActiveRecord::Base
    has_and_belongs_to_many :transactions

View

<%= form.collection_select :tag_ids, @tags, :id, :name, {}, 
    {:multiple => true} %>

Result:

<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.

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关系的多选问题4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆