Rails : assign multiple params via form_for check_box for HABTM relationship

白昼怎懂夜的黑 提交于 2019-12-11 02:49:05

问题


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

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

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

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

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.

Thanks in advance


回答1:


Try this

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

and your controller code

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


来源:https://stackoverflow.com/questions/21574404/rails-assign-multiple-params-via-form-for-check-box-for-habtm-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!