Search code examples
ruby-on-rails-4friendly-id

searching belongs_to association via friendly_id slug


An appointment belongs to a schedule. Without using friendly_id, the following code works, as expected, to build a list of appointments:

def show
    @appointments = Appointment.where(schedule_id: params[:id])
end

However, when I send the slug instead of the ID, things get more complicated. Something like Appointment.where(schedule.slug = "MYSLUG") is what I would love to do, but I ended up with this piece o' ugliness:

def show
    @appointments = Appointment.where(schedule_id: Schedule.where(slug: params[:id]))
end

It works, but it seems like I'm making it too complicated.

Suggestions to improve this code gratefully accepted.


Solution

  • I'd go with a pair of scopes. This helps keep your code readable and reusable (you get to use the same Schedule.for_slug method while searching for Schedules and Appointments).

    # class Schedule
    def self.for_slug(slug)
      where(slug: slug)
    end
    
    # class Appointment
    def self.for_schedule_slug(slug)
      joins(:schedule).
        merge(Schedule.for_slug(slug))
    end
    

    Put them together like this

    appointments = Appointment.for_schedule_slug(params[:id])