我如何在finder where子句中有条件地包含参数?

时间:2017-01-20 17:59:39

标签: ruby-on-rails arguments where ruby-on-rails-5 finder

我在PostGres 9.5中使用Rails 5。我如何在finder where子句中有条件地包含参数?我有以下

  def self.find_by_name_and_hometown_and_age(user)
    search_criteria = ["my_objects.user_id is null"]
    # Name criteria
    search_criteria.push("upper(my_object_times.name) = ?")

    # Hometown criteria
    search_criteria.push( "upper(my_object_times.city) = ?" ) 
    if user.address.state_id 
      search_criteria.push( "my_object_times.state_id = ?" ) 
    end
    if user.address.country_id
      search_criteria.push( "my_object_times.country_id = ?" ) 
    end

    # Age
    search_criteria.push( "date ? + interval '1 year' * my_object_times.age between my_objects.day - interval '1 year' and my_objects.day + interval '1 year'" ) 

    results = MyObjectTime.joins(:my_object,
                              "LEFT JOIN user_my_object_time_matches on my_object_times.id = user_my_object_time_matches.my_object_time_id").where( search_criteria.join(' and '),
                                                                                                                                "#{user.first_name.upcase} #{user.last_name.upcase}",
                                                                                                                                "#{user.address.city}",
                                                                                                                                "#{user.address.state_id}",
                                                                                                                                "#{user.address.country_id}",
                                                                                                                                user.dob ) 
  end

请注意,如果没有“user.address.state_id”字段或“user.address.country_id”字段,我在搜索中不包含条件,但我不清楚如何告诉where子句忽略这些论点。我宁愿只有一个where子句。

1 个答案:

答案 0 :(得分:0)

where子句是可链接的,所以你只需要简单的if语句

all_items = MyObjectTime.all

if some_condition
  all_items = all_items.where(...)
end

if some_other_condition
  all_items = all_items.where(...)
end

最后all_items将包含您想要的内容。