1

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 back all the line items based upon this model?

thx

Community
  • 1
  • 1
timpone
  • 19,235
  • 36
  • 121
  • 211
  • possible duplicate of [has_many :through usage, simple, beginner question](http://stackoverflow.com/questions/7524528/has-many-through-usage-simple-beginner-question) – Dan McClain Sep 23 '11 at 14:46
  • `has_many :through` allows you to get all model objects that are indirectly accessible from **one** model object, not by **all** model objects. So no, it is not supposed to work. – mliebelt Sep 23 '11 at 15:14
  • See my answer to your first question: I don't think this question makes sense in light of that. Once you fix things up, feel free to re-ask this, there is something called ["association methods"](http://stackoverflow.com/questions/1529606/how-do-rails-association-methods-work) that you can use to select collections within collections. – Andrew Vit Sep 24 '11 at 02:09

2 Answers2

3

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.

Harish Shetty
  • 64,083
  • 21
  • 152
  • 198
  • is this making the LineItems the class between Product and Invoice. What I'm trying to model is kinda screwy where each product is unique so that a 'LineItem' is really a 'Cost' for internal accounting. I only ask because most of the exaamples I've seen have used the class with two belongs_to as the joining class. thx – timpone Sep 24 '11 at 02:13
1

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

    @i.products.collect(&:line_items)
rdvdijk
  • 4,400
  • 26
  • 30