我的活动有很多事件 - 事件是活动发生的日期和时间。
在我的活动索引中,我想列出未来至少有一个事件的所有活动。
我正在使用 ransack 进行其他过滤,作为类别等。
我如何过滤关系中的大于条件?
我以为我能做到:
obj = search
.joins(:event)
.where(:events => ['end_at > ?', Date.today ])
但我得到一个错误:
undefined method `join' for #<Ransack::Search:0x007f8aa8eff918>
更新 以便提供更多上下文,我的控制器看起来像这样
def index
if (params[:oldestchild].present? && params[:oldestchild].to_i > 0) ||
(params[:youngestchild].present? && params[:youngestchild].to_i > 0)
@search = Activity
.where(' (oldest > ?z and youngest < ?) or (oldest > ? and youngest < ?) ',
params[:oldestchild], params[:oldestchild],
params[:youngestchild], params[:youngestchild],
)
.search(params[:q])
else
@search = Activity
.search(params[:q])
end
@activities = Activity.filter(params, @search, request).includes(:provider).includes(:location)
if current_parent and current_parent.children.first
@min_child_age = current_parent.min_child_age
@max_child_age = current_parent.max_child_age
end
end
我的模型有这个过滤方法:
def self.filter(params, search, request)
obj = search.result(:distinct => true)
# obj = search
# .joins(:event)
# .where(:events => ['end_at > ?', Date.today ])
if params[:within].present? && (params[:within].to_i > 0)
obj = obj.where(:location_id => self.build_locations_array(request))
end
if params[:q].present? and params[:q][:category_ids].present?
obj = obj
.joins(:categories)
.where('categories.id' => params[:q][:category_ids])
end
if params[:date_range] == "This month"
obj = obj.where(:start => (Date.today)..(Date.today.at_end_of_month))
end
if params[:date_range] == "Next month"
date = Date.today + 1.month
obj = obj.where(:start => (date.at_beginning_of_month)..(date.at_end_of_month))
end
if params[:date_range] == "Next 3 Months"
date = Date.today + 3.month
obj = obj.where(:start => (Date.today)..(date.at_end_of_month))
end
if params[:date_range] == "Whenever"
obj = obj.where("start > ?", Date.today)
end
obj.paginate(:page => params[:page], :per_page => 5)
end
更新
一种可行但相当难看的选项是使用 sql。
obj = search.result(:distinct => true)
.where("exists (select events.id from events
where events.activity_id = activities.id
and end_at > ?)", Date.today)