3

In order to avoid having to construct complicated dynamic SQL queries, I'd like to be able to just pass in nil values in my conditions, and have those ignored. Is that supported by ActiveRecord?

Here is an example.

event = Event.find(:all, :conditions => { 
                                          :title       => params[:title],
                                          :start_time  => params[:start_time], 
                                          :end_time    => params[:end_time]
                                        }).first

In that particular case, if params[:start_time] is set to nil, ActiveRecord will search for those Events that have their start_time set to null. Instead, I'd like it to just ignore start_time. How do I do that?

4

1 回答 1

6

您不必“创建复杂的动态 SQL 查询”来做您需要的事情。只需单独构建条件散列,并在创建时或创建散列后排除空值。

conditions = {}
conditions[:title] = params[:title] unless params[:title].blank?
conditions[:start_time] = params[:start_time] unless params[:start_time].blank?
conditions[:end_time] = params[:end_time] unless params[:end_time].blank?

或者

conditions = {:title => params[:title], :start_time => params[:start_time], :end_time => params[:end_time]}
conditions.delete_if {|k,v| v.blank? }

或者

conditions = params.reject {|k,v| !([:title, :start_time, :end_time]).include?(k) }

但只有当键实际上是符号时,最后一种形式才有效。在 Rails 中,params 哈希是一个 HashWithIndifferentAccess,它允许您将文本键作为符号访问。当然,如果需要,您可以只使用键数组中的文本值来包含。

然后使用您预先构建的条件哈希查询:

event = Event.find(:all, :conditions => conditions).first
于 2012-04-19T16:21:19.963 回答