我已經建立了三個模型之間的關聯,其中用戶可以has_many配方和配方belongs_to用戶。這是模型設定的:
模型用戶
has_many :reviews
has_many :recipes, through: :reviews
模型食譜
has_many :reviews
has_many :users
belongs_to :user
模型審查
belongs_to :user
belongs_to :recipe
目前,用戶和配方各有一個資料。我想將配方分配給用戶,所以我在 Rails 控制臺中執行了以下操作:
u2 = User.find_by_id(2)
r1 = Recipe.find_by_id(1)
u2.recipes = r1
然后出現“NoMethodError(#Recipe:0x0000560632fde3d0 的未定義方法‘每個’)”。
我無法理解,has_many或者has_one應該生成recipes和recipes=方法,為什么這不起作用?
uj5u.com熱心網友回復:
它不起作用,因為您試圖將單個記錄分配給has_many關聯。您得到的原因undefined method 'each'是生成的 setter 需要一個可以迭代的陣列或關聯。例如:
user = User.find(2)
user.recipies = Recipe.where(id: 1)
但是將單個記錄分配給 ahas_many或has_and_belongs_to_many關聯的慣用正確方法是使用 shovel 方法:
u2 = User.find_by_id(2)
r1 = Recipe.find_by_id(1)
u2.recipes << r1
通過間接關聯,Rails 將在連接表中隱式創建行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460247.html
標籤:轨道上的红宝石
