2
我是第一个自己的项目的rails noob。Rails:通过form_for check_box为HABTM关系分配多个参数
我使用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
我的目标是做一个形式,创造酒的情况下,包括在酒可以购买的商店。这里是我的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 %>
我试过很多东西,花了几个小时就这一点,但无法找到解决方案。别的不说我看了一下这些问题,但我无法得到它的工作:
- 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
最后我得到了一个
undefined method `merge' for 3:Fixnum
只要让我知道你是否需要任何其他细节来处理t他的问题,还是已经有一个关于我已经错过的问题。
在此先感谢
您还可以简化您crreate方法:'@wine = Wine.new(PARAMS [:酒]) @ wine.shops << Shop.find(params [:shops]) end' – BroiSatse
我仍然得到'未定义的方法'合并'3:Fixnum',其中3是一个sh的id op – SBfrr
@SBfrr,更新了我的回答 – Santhosh