My application consists of these five models: A supermarket can have different categories of products and the products in these categories can be produced by several brands.
Now I want to have one (or two) Selection-field(s) in my supermarket-form in which I can select one element in Category with its name appearing and one or more element(s) in Brand with its name appearing, so this could be stored in Origin.
I think I could use collection_select
, but how do I utilize it here?
class Supermarket < ActiveRecord::Base
has_many :supplies
has_many :origins, :through => :supplies
end
class Supply < ActiveRecord::Base
belongs_to :origin
belongs_to :supermarket
end
class Origin < ActiveRecord::Base
belongs_to :category
belongs_to :brand
end
class Category < ActiveRecord::Base
has_many :origins
end
class Brand < ActiveRecord::Base
has_many :origins
end
Probably, I also have to tweak the models...
Edit
To clarify what the outcome of the form should be:
In the form to edit Supermarkets I want to select a Category of products and the corresponding Brands so that I know, which Category and which Brands in this Category is/are sold in this specific Supermarket:
Supermarket (Form):
Name of Supermarket: Walmart
Category (Select one):
- Cola (Category_ID 1)
- Cornflakes (Category_ID 2)
- ...
Brand (multiple Select)
- The Coca-Cola Company (Brand_ID 1)
- PepsiCo (Brand_ID 2)
- Kellogg Company (Brand_ID 3)
- ...
This should create entries in Origin like:
Supermarket_ID Category_ID Brand_ID 1 1 1 1 1 2 2 1 2 2 2 3 ... ... ...
/Edit
Edit 2
According to the answer to this question, I could create or select an entry via console like this:
walmart = Supermarket.create(:name => "Walmart");
cornflakes = Category.create(:name => "Corn Flakes");
kellogs = Brand.create(:name => "Kellog's");
walmart.origins.create(:category_id => cornflakes, :brand_id = kellogs)
How can I make use of this via a form? How could I utilize select
or collection_select
or is there even another helper I could use?
/Edit 2