[英]Setting up Rails Controller for the through in has_many through relationship
[英]Setting up has_many through correctly in Rails
昨天我問了一個有關在Rails中的模型之間設置has_and_belongs_to_many關系的問題。 我最終使這些關系正常工作,但是,我意識到我需要在聯接表中存儲其他信息,這意味着我應該通過與聯接模型的關系來使用has_many(我想?)。
我現在有一個配方模型,成分模型和一個數量聯接模型。 每個食譜都有很多成分,反之亦然。 配方中的每種成分在某種單位類型中都有一定數量。
到目前為止,這是我的設置:
模型/recipe.rb
class Recipe < ActiveRecord::Base
has_many :amounts
has_many :ingredients, :through => :amounts
end
型號/ingredient.rb
class Ingredient < ActiveRecord::Base
has_many :amounts
has_many :recipes, :through => :amounts
end
型號/數量.rb
class Amounts < ActiveRecord::Base
belongs_to :recipes
belongs_to :ingredients
end
MySQL表:
$ mysql > show columns from recipes;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| desc | text | NO | | NULL | |
| image_url | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
mysql> show columns from ingredients;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
mysql> show columns from amounts;
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| recipe_id | int(11) | NO | | NULL | |
| ingredient_id | int(11) | NO | | NULL | |
| amount | int(11) | NO | | NULL | |
| units | varchar(255) | NO | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
我想我已經正確設置了關系...我只是不確定如何正確添加到聯接模型/表中,然后訪問這些值。 例如,我可以調用@ recipe.ingredients並返回所有關聯的成分嗎?
編輯:對於我要做什么的困惑,我深表歉意。
當我使用has_and_belongs_to_many關系時,我可以使用'<<'推送到@ recipe.ingredients,並自動將joint表與recipe_id和Ingredient_id插入。 但是,由於使用了連接表中的其他屬性,因此在使用has_many through時,此方法似乎不起作用。
我將如何創建這些關聯?
您可以直接讀取並分配給recipe.ingredients
,它將自動寫入連接表。
但是您不太可能需要它,因為您需要該數量的其他信息。 您可能需要使用嵌套屬性為表單中的數量更新/創建配方。
在數量模型中,考慮每個配方成分的唯一性約束。
希望這有所幫助
建立has_many :through
關聯是Rails的一些魔術。 您將有權訪問has_many
關聯為聯接表和相關表設置的所有方法。 Rails會自動處理所有關聯。
在這里看看Rails指南。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.