【问题标题】:Rails : assign multiple params via form_for check_box for HABTM relationshipRails:通过 form_for 复选框为 HABTM 关系分配多个参数
【发布时间】:2014-03-01 17:11:08
【问题描述】:

我是第一个自己的项目的 Rails 菜鸟。

我使用 has_and_belongs_to_many 关系链接了两个模型:Wine 和 Shop。为了简单起见,葡萄酒可以在不同的商店出售,而特定的商店可以出售许多不同的葡萄酒。以下是模型:

class Shop < ActiveRecord::Base
 has_and_belongs_to_many :wines
end

class Wine < ActiveRecord::Base
  has_and_belongs_to_many :shops
end

我的目标是制作一个表单来创建 Wine 的实例,包括可以购买葡萄酒的商店。这是我的 wines_controller :

  def new
    @wine = wine.new
    @shops = Shop.all

   respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @wine }
    end
  end

 def create
    @wine = Wine.new(params[:wine])
    params[:shops].each do |id|
      @wine.shops << Shop.find(id)
    end 
end

这是我在新视图中呈现的 _form 视图:

<%  @shops.each do |t|  %>
<%= f.label t.name  %>
<%= f.check_box :shops, t.id %>
<% end %>

我已经尝试了很多方法并为此花费了数小时,但找不到解决方案。除其他外,我查看了这些问题,但无法使其正常工作:

最后我得到了一个

undefined method `merge' for 3:Fixnum

如果您需要任何其他详细信息来处理此问题,或者是否已经存在我错过的有关此问题的问题,请告诉我。

提前致谢

【问题讨论】:

    标签: ruby ruby-on-rails-3 checkbox has-and-belongs-to-many


    【解决方案1】:

    试试这个

    <%  @shops.each do |t|  %>
      <%= f.label t.name  %>
      <%= check_box_tag "shops[]", t.id %>
    <% end %>
    

    和你的控制器代码

    def create
      @wine = Wine.new(params[:wine])
      @shops = Shop.find params[:shops]
      @wine.shops = @shops
      ..
    

    【讨论】:

    • 你也可以简化你的创建方法:` @wine = Wine.new(params[:wine]) @wine.shops
    • 我仍然得到undefined method merge' for 3:Fixnum`,其中 3 是其中一家商店的 id
    • @Santosh 已经尝试过那个 ;) 我得到了 undefined method check_box_tag' #<:helpers::formbuilder:0x3c774f0>
    • @BroiSatse 对此表示感谢,但似乎并没有解决视图问题。
    • @Santosh - 您将获得 Wine 的“未知属性“商店”。您需要将@shops 分配移至@wine 分配并将其更改为@shops = Shop.find params[:wine].delete(:shops)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2017-11-13
    相关资源
    最近更新 更多