Rails:通过form_for复选框为HABTM关系分配多个参数 [英] Rails : assign multiple params via form_for check_box for HABTM relationship

查看:90
本文介绍了Rails:通过form_for复选框为HABTM关系分配多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从事第一个项目的Rails菜鸟。

I'm a rails noob working on my first own project.

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

I got two models linked using a has_and_belongs_to_many relationship : Wine and Shop . To make it simple a wine can be sold in different shops and a specific shop can sell many different wines. Here are the models :

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:

My goal is to make a form to create instances of Wine including the Shops where the wine can be purchased. Here is my 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视图在新视图中呈现:

Here is my _form view rendered in new view :

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

我尝试了很多事情,花了数小时,但找不到解决方案。除其他事项外,我查看了这些问题,但无法正常工作:

I've tried many things and spent hours on this but can't found the solution. Among other things I had a look at those issues but I could not get it working :

  • Rails create form for model with many to many relation
  • update values of checkbox with HABTM relationship -- Rails
  • Creating multiple records in a HABTM relationship using a collection_select - Rails

最后在HABTM关系中创建多条记录

Lastly I got an

undefined method `merge' for 3:Fixnum

请告诉我是否需要其他详细信息来解决此问题,或者是否已经有一个我遗漏的问题。

Just let me know if you need any other details to deal with this issue or if there is already a question about this that I have missed.

预先感谢

推荐答案

尝试一下

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

这篇关于Rails:通过form_for复选框为HABTM关系分配多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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