Ruby on rails 在:直通模型上设置Rails属性
考虑以下(人为)示例模型关系:Ruby on rails 在:直通模型上设置Rails属性,ruby-on-rails,Ruby On Rails,考虑以下(人为)示例模型关系: class Yolk < ActiveRecord::Base has_many :whites, through: :eggs # has all sorts of interesting properties, like powderiness end class Egg < ActiveRecord::Base belongs_to :yolk belongs_to :white # The egg has a colo
class Yolk < ActiveRecord::Base
has_many :whites, through: :eggs
# has all sorts of interesting properties, like powderiness
end
class Egg < ActiveRecord::Base
belongs_to :yolk
belongs_to :white
# The egg has a color property!
end
class White < ActiveRecord::Base
has_many :yolks, through: :eggs
# has its own set of properties, such as shininess
end
classyolk
(注意鸡蛋有一个颜色属性-这很重要!)
如果我想在设置鸡蛋本身的颜色属性的同时将蛋黄添加到白色(创建鸡蛋),我该如何做
给定一个名为White
的White
实例和一个名为Yolk
的Yolk
实例:
white.yolks
如果我想在设置鸡蛋本身的颜色属性的同时将蛋黄添加到白色(创建鸡蛋),我该如何做
直接回答这个问题
white.eggs.create!(yolk: yolk, color: 'blue')
考虑到,white
是white
的一个实例,yelk
是yelk
的一个实例
注意:您只需将has_many:ovgs
添加到White
和yelk
模型中,即可以相同的方式进行查询。在irb
中,我可以手动更新White.yelks
变量,方法是首先调用用于获取White
(例如White.last
),但这在应用程序或其测试套件中既不方便也不可行。这非常有效,您只需将has\u many:eggs
添加到White
。谢谢@是的。我以为你已经添加了它,请对我们隐藏它:)我做了,我只是想确保这是为未来的观众指定的;您可能希望将其添加到您的答案中。