[英]How two classes of model are accessing each other?
查看具有此結構的rails示例及其模型:
在代碼中,我們有:
class LineItem < ActiveRecord::Base
belongs_to :product
belongs_to :cart
attr_accessible :cart_id, :product_id
end
在“ Product”類的模型中,有一個定義如下的方法:
class Product < ActiveRecord::Base
has_many :line_items
private
# ensure that there are no line items referencing this product
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line Items present')
return false
end
end
那么,我們甚至在哪里定義了像:line_items這樣使用的line_items? 它怎么知道它指的是什么? 它是否知道基於某些命名約定的魔術? 它如何將:line_items連接到LineItems類? 如果您能解釋這兩個如何連接在一起,那就太好了。
是的,它正在發揮作用。 定義關聯時(在這種情況下,通過使用belongs_to
和has_many
,Rails基於關聯對象的名稱創建一堆方法。因此,在這種情況下,產品中添加了.line_items
方法,該方法返回一個Relation(基本上是一個代表數據庫查詢的對象),當代碼使用該Relation執行某些操作時,它將執行查詢並返回LineItem對象的數組。
這也是Rails知道您執行諸如分配關聯對象( @line_item.product = Product.find(3)
)之類的事情或創建新的關聯對象( @product.create_line_item(:title => 'foo')
)。
本指南提供了詳細信息,包括由各種關聯創建的方法的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.