Search code examples
ruby-on-railsmodel-associations

Rails finding has_many child by child key, in a fancy way


I'm using Rails 4

Suppose I have, for example, a Week model that has_many Days

I know I can get a specific day with something like

Week.take.days.where{ :week_day => 'mon' }.first

But is there a simple way to get each day with something like

Week.take.mon

instead?

By "simple" I mean that I don't what to manually define a method or a relation for each day.


Solution

  • You can define a scope:

    scope :having_week_day, ->(wday) { where(week_day: wday) }
    

    And use it like this:

    Week.having_week_day('mon')