Rails: has_one of a has_many association with criteria -


i have instance method works declare has_one relationship. how can define has_one through relationship has_many through?

this method works:

class facility   has_many :locations   has_many :events, though: :locations    def upcoming_event     events.       where('events.start_time >= ?', time.zone.now).       order('events.start_time asc').       first   end end 

this relationship doesn't:

has_one :upcoming_event, -> {   where('start_time >= ?', time.zone.now).   order('start_time asc') }, through: :locations, class_name: "event" 

following meagar's suggestion, there's alternative should accommodate preference group related functionality:

class facility   has_many :locations   has_many :events, though: :locations     def upcoming       where('start_time >= ?', time.zone.now).order('start_time asc')     end   end end 

this makes clear upcoming method on relationship, not on event model. allows write:

facility.events.upcoming 

which me (and opinion) communicates intent , hierarchy more facility.upcoming_events


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -