【问题标题】:searching belongs_to association via friendly_id slug通过friendly_id slug搜索belongs_to关联
【发布时间】:2015-04-06 16:33:39
【问题描述】:

约会属于日程安排。在不使用 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

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

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

【问题讨论】:

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


    【解决方案1】:

    我会选择一副瞄准镜。这有助于使您的代码保持可读性和可重用性(您可以在搜索日程安排和约会时使用相同的 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])
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      • 2017-08-29
      相关资源
      最近更新 更多