在 Rails 控制台中绑定两个 table 数据时遇到 NoMethodError
Encountered NoMethodError when binding two table data in Rails console
我在三个模型之间建立了关联,其中用户可以 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
目前User和Recipe各有一个数据。我想将食谱分配给用户,所以我在 Rails 控制台中执行了以下操作:
u2 = User.find_by_id(2)
r1 = Recipe.find_by_id(1)
u2.recipes = r1
然后出现“NoMethodError (undefined method `each' for #Recipe:0x0000560632fde3d0)”。
我无法理解,has_many
或 has_one
应该生成 recipes
和 recipes=
方法,为什么这不起作用?
它不起作用,因为您正试图将单个记录分配给 has_many
关联。你得到 undefined method 'each'
的原因是生成的 setter 需要一个数组或一个可以迭代的关联。例如:
user = User.find(2)
user.recipies = Recipe.where(id: 1)
但是将单个记录分配给 has_many
或 has_and_belongs_to_many
关联的惯用正确方法是使用 shovel 方法:
u2 = User.find_by_id(2)
r1 = Recipe.find_by_id(1)
u2.recipes << r1
使用间接关联 Rails 将在连接中隐式创建行 table。
我在三个模型之间建立了关联,其中用户可以 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
目前User和Recipe各有一个数据。我想将食谱分配给用户,所以我在 Rails 控制台中执行了以下操作:
u2 = User.find_by_id(2)
r1 = Recipe.find_by_id(1)
u2.recipes = r1
然后出现“NoMethodError (undefined method `each' for #Recipe:0x0000560632fde3d0)”。
我无法理解,has_many
或 has_one
应该生成 recipes
和 recipes=
方法,为什么这不起作用?
它不起作用,因为您正试图将单个记录分配给 has_many
关联。你得到 undefined method 'each'
的原因是生成的 setter 需要一个数组或一个可以迭代的关联。例如:
user = User.find(2)
user.recipies = Recipe.where(id: 1)
但是将单个记录分配给 has_many
或 has_and_belongs_to_many
关联的惯用正确方法是使用 shovel 方法:
u2 = User.find_by_id(2)
r1 = Recipe.find_by_id(1)
u2.recipes << r1
使用间接关联 Rails 将在连接中隐式创建行 table。