Ruby on Rails的“哪里”方法Postgres

时间:2018-08-29 16:35:01

标签: ruby-on-rails rails-activerecord

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

我正在使用控制器中的参数[county_id:]进行过滤。

我想说的是County_id为0的所有事件。

关联为Event.schedules.county 我已经将其用于类别的类似参数搜索

事件归属于:category 类别has_many:事件

    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等

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

下面的答案。感谢@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