2015-04-06 53 views
0

约会属于时间表。如果不使用friendly_id,下面的代码工作,如预期,打造约会列表:通过friendly_id slug搜索belongs_to协会

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

然而,当我送塞,而不是ID的,事情变得更加复杂。 喜欢的东西Appointment.where(schedule.slug =“MYSLUG”)是我喜欢做的,但我结束了这片O'丑:

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

它的工作原理,但它似乎像我因为它太复杂了。

建议改善此代码感激地接受。

回答

0

我会去与一对范围。这有助于保持代码的可读性和可重用性(您可以在搜索计划和约会时使用相同的Schedule.for_slug方法)。

# 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 

把它们放在一起这样

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