【问题标题】:Ruby on Rails "Where" method PostgresRuby on Rails“Where”方法 Postgres
【发布时间】:2019-02-04 12:39:19
【问题描述】:

我在这里很困惑。我的事件模型有很多时间表。在我的日程表模型中,我有日期和县属性。计划模型属于一个事件。

我正在通过我的控制器中的 param[county_id:] 进行过滤。

假设我想查找所有县 ID 为 0 的事件。

关联是 Event.schedules.county 我已经让它适用于类别的类似参数搜索

事件 belongs_to :category 类别 has_many :events

    if params[:category].present?
        @category_id = Category.find_by(name: params[:category]).id
        @events = Event.where(category_id: @category_id).order("created_at DESC")
    elsif params[:county].present?
        @schedules = Schedule.find_by(county: params[:county])
    else
        @events = Event.where(status: 1).order("created_at DESC")
    end

如您所见。我可以抓取一组时间表,并且可以看到每个时间表都附加了 event_id。我怎样才能使我的前端可以保持循环通过@events 变量而不是循环通过@schedules 变量并且必须去 schedule.event.title 等

任何帮助将不胜感激。

【问题讨论】:

  • 这就是joins 的用途。您可以在 Active Record 查询接口指南Section 12 Joining Tables 中了解它。顺便说一句,这不是 Postgres 的东西,而是 AR 的东西。
  • 加入。迷人的。想了那么多。他们让我头晕目眩。谢谢@jvillian

标签: ruby-on-rails rails-activerecord


【解决方案1】:

在下面回答。感谢@jvillian 为我指明了正确的方向。

    # simple filter for category select on idex page    
elsif params[:category].present?
    @category_id = Category.find_by(name: params[:category]).id
    @events = Event.where(category_id: @category_id).order("created_at DESC")
elsif params[:county].present?
    @events = Event.joins(:schedules).where(schedules: {county: params[:county]}).all
else
    @events = Event.where(status: 1).order("created_at DESC")
end

【讨论】:

  • 很高兴能为您提供帮助。顺便说一句,我不相信你最后真的需要all。当您访问@events 时将触发查询。但是,这是一个虚无。
  • 好的,谢谢。是的,自 sql 天以来就避免了连接。让我头晕目眩。主动记录助手绝对有助于更轻松地了解它。谢谢
  • 当然可以。你欠我一品脱。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多