开发者

Related to result of eager loading in ROR Active Record

I have an Invoice model which belongs to Customer (and of course Customer has_many invoices).

If I do:

{
  @invs = Invoice.find(
    :all, 
    :include => ["customer"], 
    :conditions => ['somecondition']
  )
}

The class of @invs is an Array and I can see all the attributes for the 6th invoice in the array if I do: @invs[5]. However at that point I don't see the associated Customer record attributes. To get that I need to do @invs[5].customer.

My question is what is the Ruby structure that allows access to the customer record from the invoice record? I want to create a new arbitrary record of SomeClass and attach that to the invoice record within the recordset so that I can do @inv[5].someclass. Is that possible? and if so how?

[EDIT - FULL STORY] The following tries to explain why I'm asking the question.

Although my Invoice model relates to a single table in the Db my Customer record can get archived and moved to another table called Archcustomer which is identical to Customer in structure. So I have additional associations like Invoice belongs_to Archcustomer and Archcustomer has_many Invoices.

I need to get a list of Invoices together with their associated customer record (regardless of where it's held i.e. Customer or Archcustomer) but sorted by Customer.category_id and Customer.id and Invoice.id.

In my original example above of @invs I am including the customer record and I could include the :order => 'customer.category_id, customer.id, invoice.id' clause but where the customer is archived the customer record is nil.

So I thought I would do the following:

{
  @invs.each do |inv|
    next if inv.customer != nil
    archcust = Archcustomer.find(inv.customer_id) #开发者_开发技巧since it's not in customer get it from Archcustomer
    inv.customer.category_id = archcust.category_id 
    etc...
    ...
    end
}

and then use @inv.sort_by. However that complains because I'm trying to allocate a value to customer.category_id of Nil class.

That's when I thought if I could attach an arbitrary record to Invoice I could fill in the info from either Archcustomer or Customer and have a common set of attributes to call my sort_by on.

Of course if there is some other way of achieving my set of Invoices ordered as I want them then I'll be happy to go with that.


In your invoice model (assuming you have your Archcustomer relationship in place):

class Invoice < ActiveRecord::Base
  def customer_record
    customer or archcustomer
  end
end

Use @invoice.customer_record instead of @invoice.customer or @invoice.archcustomer when you need to get a record from any available source. .include both when you're loading.

Don't bother assigning stuff to an imaginary Customer when you already have a real Archcustomer. Just run sort_by on customer_record.category_id.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜