通过 friendly_id slug 搜索 belongs_to 关联
searching belongs_to association via friendly_id slug
约会属于日程安排。在不使用 friendly_id 的情况下,以下代码可以按预期运行以构建约会列表:
def show
@appointments = Appointment.where(schedule_id: params[:id])
end
但是,当我发送 slug 而不是 ID 时,事情变得更加复杂。
Appointment.where(schedule.slug = "MYSLUG") 之类的东西是我喜欢做的,但我最终得到了这件丑陋的东西:
def show
@appointments = Appointment.where(schedule_id: Schedule.where(slug: params[:id]))
end
它有效,但我好像把它弄得太复杂了。
感谢接受改进此代码的建议。
我会带一对示波器。这有助于保持您的代码可读性和可重用性(您可以在搜索日程安排和约会时使用相同的 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])
约会属于日程安排。在不使用 friendly_id 的情况下,以下代码可以按预期运行以构建约会列表:
def show
@appointments = Appointment.where(schedule_id: params[:id])
end
但是,当我发送 slug 而不是 ID 时,事情变得更加复杂。 Appointment.where(schedule.slug = "MYSLUG") 之类的东西是我喜欢做的,但我最终得到了这件丑陋的东西:
def show
@appointments = Appointment.where(schedule_id: Schedule.where(slug: params[:id]))
end
它有效,但我好像把它弄得太复杂了。
感谢接受改进此代码的建议。
我会带一对示波器。这有助于保持您的代码可读性和可重用性(您可以在搜索日程安排和约会时使用相同的 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])