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

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -