通过friendly_id slug搜索belongs_to association

时间:2015-04-06 16:33:39

标签: ruby-on-rails-4 friendly-id

约会属于时间表。如果不使用friendly_id,以下代码可以正常工作,以构建约会列表:

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

然而,当我发送slu而不是ID时,事情会变得更复杂。 像Appointment.where(schedule.slug =" MYSLUG")之类的东西就是我喜欢做的事情,但我最终得到了这篇文章o'丑陋:

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

它有效,但似乎我太复杂了。

感谢接受改进此代码的建议。

1 个答案:

答案 0 :(得分: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])
相关问题