Search code examples
ruby-on-rails-3belongs-to

How to get records based on info in Rails belongs_to record?


I have 2 models TourHdr and TourDetail. TourDetail belongs_to tour_hdr and TourHdr has_many tour_details. TourHdr also has an attribute called status.

I want to define a method in TourDetail which will give me all TourDetails where the status field in the associated TourHdr record = Live.

I tried the following:

def self.status(status)
  where(:tour_hdr.status == status)
end

status here can be 'Live' or 'Cancelled'.

Rails complains that there is no tour_hdr method for Class TourDetail. What is the correct syntax here?

In the console if I do:

td = TourDetail.first
puts td.tour_hdr.status

It works fine. I'm guessing it's because td is an 'Instance' of TourDetail rather than the class.


Solution

  • joins(:tour_hdr).where(:tour_hdrs => {:status => status})