我一直在玩铁轨,而且我很难理解当我把东西插入模型时,外键如何自动填入模型表中。例如,在Cart与Ingredients的1:N表关系中(假设没有制作推车),如果我编码:
# create cart and couple of ingredients
cart1 = Cart.create()
jelly = Ingredient.create()
pb = Ingredient.create()
# push jelly, and pb, into cart1
cart1.ingredients << jelly
cart1.ingredients << pb
# pb and jelly cart_id is now populated
pb.cart_id
>>1
jelly.cart_id
>>1
除了将配料推入购物车之外,rails如何填充外国ID,cart_id,列,而不需要做任何事情?
答案 0 :(得分:2)
你可以想象这样的过程:
# creates cart with id=1
cart = Cart.create
# creates ingredient with card_id=nil
jelly = Ingredient.create
# It's one-to-many relation, which knows that
# the name of the foreign key is cart_id.
# How does it know?
# Rails uses conventional logic here:
# if you don't name things explicitly then Rails
# will guess them for you.
# Name of the model is Cart, so the foreign key is cart_id.
cart.ingredients
# One-to-many relation receives some object.
# Relation asks object: do you have method cart_id=?
# Object replies: yes, I have
# Relation then takes primary key (id in this case)
# from cart (=1) and places it into object's cart_id field.
cart.ingredients << jelly
jelly.cart_id # => 1
答案 1 :(得分:0)
作为per:
按照惯例,Rails假定用于保存外来的列 此模型上的键是带有后缀
_id
的关联的名称 添加。:foreign_key
选项允许您设置外部名称 直接关键
这虽然专门针对belongs_to
关联进行了描述,但解释了Rails如何处理foreign_keys
。
您的系统中的每个对象都可以由ActiveRecord ORM 关联。如果您有has_many
,belongs_to
或has_and_belongs_to_many
关系,ActiveRecord将根据自己的逻辑填充外键(如上所述),或者如果您在模型中明确设置它。 / p>
所以当你有:
@cart.ingredients #-> ActiveRecord method populates foreign key of child objects with cart_id