Drop-Down-Menu for Many-to-Many relation in rails using nested attributes

隐身守侯 提交于 2019-12-30 05:24:08

问题


I have three tables via many-to-many-association: Supermarket, Product and Supply. Each Supermarket can hold many products and each product can be sold in many supermarkets. The association is build via the Supply-model.

Supermarket:

class Supermarket < ActiveRecord::Base
  attr_accessible :name, :address, :products_attributes

  has_many :supplies
  has_many :products, :through => :supplies

  accepts_nested_attributes_for :products
end

Product:

class Product < ActiveRecord::Base
  attr_accessible :name, :supermarkets_attributes

  has_many :supplies
  has_many :supermarkets, :through => :supplies
  accepts_nested_attributes_for :supermarkets
end

Association via Supply:

class Supply < ActiveRecord::Base
  attr_accessible :supermarket_id, :product_id

  belongs_to :supermarket
  belongs_to :product
end

I have created the scaffolds and populated the Supermarket-table. In my Product form, i want to use one (or more) drop-down-menu(s) to select the correspondent Supermarket-name(s). Goal is to create a new product while also creating the association via the Supply-table. What should the code look like in form and/or controller for the products if I want to select the corresponding supermarkets from there?


回答1:


In you products form you need to add this line...

<%= collection_select(:product, :supermarket_ids, SuperMarket.all, :id, :name, {}, { :multiple => true } )%>

You also shouldn't need to use an accepts_nested_attributes for this, the many to many association you already have set up should take care of the rest.




回答2:


I think in views

<%= f.collection_select "super_market_ids[]",@super_markets,:id,:name,{},{:multiple=>"multiple'} %>

I am not sure about super_market_ids or super_market_ids[] and syntax just verified once.

In select tag if you want checkbox type multi select there is an chosen library that will help you to build nicer UI,



来源:https://stackoverflow.com/questions/12406583/drop-down-menu-for-many-to-many-relation-in-rails-using-nested-attributes

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