ImpostorIsAsking
ImpostorIsAsking

Reputation: 73

using order method in third association field

class Order
  has_many :order_details
end

class OrderDetail
  belongs_to :order
  belongs_to :person
end

class Person
  has_one :profile
  delegate :first_name, last_name
end

class Profile

end

I'm currently iterating the order details in my view and try to sort or order by last name how can I achieve this?

I'm using this in my view

@order_details.joins(:person).order('last_name ASC').each do |detail|

should I use sort? or order?

this is my error

column "last_name" does not exist

Upvotes: 0

Views: 55

Answers (2)

Tun
Tun

Reputation: 1447

@order_details.joins(order: :person).order('last_name ASC')

should do the trick.

The reason is you do not have direct association to person from order_details (it is via order). It is called Nested Join and you can reference API here

The names passed to joins methods are not the table names, they are association names.

Upvotes: 1

spickermann
spickermann

Reputation: 106952

Just add the table name to the the order cause:

@order_details.joins(:person).order('people.last_name ASC')

Upvotes: 1

Related Questions