我有一段似乎可以工作的代码。我只是认为可能有更好的方法来实现所需的工作。问题是使用未知的参数列表构建 ActiveRecord 查询。
这是代码:
query_string = String.new
query_values = []
unless params[:organization][:name].blank?
query_string << 'name = ?'
query_values << params[:organization][:name]
end
unless params[:organization][:national_id].blank? && params[:organization][:vat_id].blank?
raise RequestParamsException.new('National ID or Vat ID given without country') if params[:organization][:country].nil?
country_id = Country.find_by_name(params[:organization][:country]).pluck(:id)
unless params[:organization][:national_id].blank?
query_string << ' OR ' unless query_string.empty?
query_string << '(national_id = ?'
query_values << params[:organization][:national_id]
query_string << ' AND ' << 'country_id = ?)'
query_values << country_id
end
unless params[:organization][:vat_id].blank?
query_string << ' OR ' unless query_string.empty?
query_string << '(vat_id = ?'
query_values << params[:organization][:vat_id]
query_string << ' AND ' << 'country_id = ?)'
query_values << country_id
end
end
known_organizations = query_string.blank? ? [] : Organization.where(query_string, query_values).uniq
当给出增值税或国民 ID 时需要国家,因为它们在模型中的范围内:
class Organization < ActiveRecord::Base
#======================VALIDATIONS=========================
validates :national_id, :uniqueness => { :scope => :country_id }, :allow_blank => true
validates :vat_id, :uniqueness => { :scope => :country_id }, :allow_blank => true
validates :country, :presence => true
end