简体   繁体   English

了解Rails活动记录关联

[英]Understanding rails active record association

I was reading a book for agile web development and I found this code 我在读一本关于敏捷Web开发的书,发现了这段代码

application controller 应用控制器

  private    
  def current_cart
    Cart.find(session[:cart_id])
  rescue ActiveRecord::RecordNotFound
    cart = Cart.create
    session[:cart_id] = cart.id
    cart
  end

line items controller 订单项控制器

def create
  @cart = current_cart
  product = Product.find(params[:product_id])
  @line_item = @cart.line_items.build(:product => product)
  respond_to do |format|
   if @line_item.save
     format.html { redirect_to(@line_item.cart,
            :notice => 'Line item was successfully created.') }

I don't understand the following two lines 我不明白以下两行

@line_item = @cart.line_items.build(:product => product)
format.html { redirect_to(@line_item.cart,
       :notice => 'Line item was successfully created.') }

@cart holds the value of cart_id then what @cart.line_items point and what is the use of build method here? @cart持有的价值cart_id那么什么@cart.line_items指出,什么是利用这里构建方法的?

Also what @line_item.cart means here? @line_item.cart在这里意味着什么? which action will be called? 哪个动作会被调用?

Okay, let's start with @cart . 好吧,让我们从@cart开始。 As phoet says, it is not a simple integer. 正如phoet所说,它不是一个简单的整数。 It is set by Cart.find(session[:cart_id]) , so it is an instance of the Cart model based off a row in the database. 它由Cart.find(session[:cart_id]) ,因此它是基于数据库中某一行的Cart模型的实例。

The Cart model presumably inherits from ActiveRecord::Base which has all the logic for has_many (and other) associations (relations) between models. Cart模型大概继承自ActiveRecord::Base ,该模型具有模型之间has_many(及其他)关联(关系)的所有逻辑。 So, I would expect to see at least 所以,我希望至少看到

def Cart < ActiveRecord::Base
    has_many :line_items
end

in the Cart model. Cart模型中。

So, when you call @cart.line_items you get something that is conceptually a list of that cart's line items through the association set up by the call to has_many . 因此,当您调用@cart.line_items时,通过对has_many的调用建立的关联,您会得到概念上该购物@cart.line_items项目列表的内容。 Calling build on that results in a new (as of yet, unpersisted) instance of the LineItem model that has its cart_id value set to @cart.id . 在此build上调用build会导致LineItem模型的新实例(至今尚未持久),其cart_id值设置为@cart.id

I hope that clears things up a bit. 我希望这可以使事情变得简单。 Rails associations are tricky business. Rails协会是一项棘手的业务。

Your assumption is not correct. 您的假设不正确。 @cart holds a Cart object from the current_cart method. @cart拥有current_cart方法中的Cart对象。 It's either new, or the one held in the session. 它要么是新的,要么是会话中举行的。

So @cart.line_items works with the has_many relation of Cart and line_items.build will setup a new LineItem to be saved to the database on @line_tem.save . 因此, @cart.line_itemsCarthas_many关系配合使用, line_items.build将设置一个新的LineItem并保存到@line_tem.save上的数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM