Вопрос

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 :

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

Это было полезно?

Решение

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
  ..
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top