ruby on rails 4 - searching belongs_to association via friendly_id slug -
ruby on rails 4 - searching belongs_to association via friendly_id slug -
an appointment belongs schedule. without using friendly_id, next code works, expected, build list of appointments:
def show @appointments = appointment.where(schedule_id: params[:id]) end
however, when send slug instead of id, things more complicated. appointment.where(schedule.slug = "myslug") love do, ended piece o' ugliness:
def show @appointments = appointment.where(schedule_id: schedule.where(slug: params[:id])) end
it works, seems i'm making complicated.
suggestions improve code gratefully accepted.
i'd go pair of scopes. helps maintain code readable , reusable (you utilize same schedule.for_slug method while searching schedules , 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 this
appointments = appointment.for_schedule_slug(params[:id])
ruby-on-rails-4 friendly-id
Comments
Post a Comment