开发者

has_many :through and getting associated items

This is a follow-up to this question has_many :through usage, simple, beginner question

Basically, I'd like to have a function in my Invoice class that gets all the LineItems but the following is not working:

so:

> @i=Invoice.find(1)      # good   
> @i.products             # good works well  
> @i.products.line_items  # not working, undefined method line_items  

based upon associations in previous question, should this be working? I think it should if I access products directly:

> @p=Product.find(1)      # good  
> @p.line_items           # also good

How can I get 开发者_如何学Pythonback all the line items based upon this model?

thx


Assuming you have following models:

class Invoice
  has_many :line_items
  has_many :products, :through => :line_items
end

class LineItems
  belongs_to :invoice
  belongs_to :product
end

class Product
  has_many :line_items
  has_many :invoices, :through => :line_items
end

You can do the following:

@i=Invoice.find(1) # good
@i.products # good works well
@i.line_items # all the line_items associated with the invoice.


@i.products returns a collection of Products. You need to collect all the line items:

    @i.products.collect(&:line_items)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜