Rails新手:在activerecord中附加条件?

时间:2010-12-03 05:43:12

标签: ruby-on-rails activerecord

我有一个用于过滤查询的表单。一些表单属性是可选的;我只是想知道如果(并且只有)它们有一个设定值,如何将它们作为activerecord条件追加?

其中有一些,所以我宁愿不为每个潜在价值模式单独查询。有什么建议吗?

举一个具体的例子:

people = People.paginate(
  :all,
  :include => [:people_postcodes, :people_specialties, :people_states],
  :conditions => ["people_specialties.people_type_id = %s AND (people_postcodes.postcode_id = %s OR people_states.state_id = %s)" % [self.people_type_id, postcodeid.id, stateid]], 
  :page => page, 
  :per_page => 16
)

只有填充了可选的“国籍”属性,我才能最好地创建额外条件(比如“国籍”)?

1 个答案:

答案 0 :(得分:2)

首先,你的条件有点不安全。你正在进行基本的ruby文本替换,这将让站点用户注入他们想要的任何恶意sql。相反,将其格式化为:

people = People.paginate(
  :all,
  :include => [:people_postcodes, :people_specialties, :people_states],
  :conditions => ["people_specialties.people_type_id = ? AND (people_postcodes.postcode_id = ? OR people_states.state_id = ?)", self.people_type_id, postcodeid.id, stateid], 
  :page => page, 
  :per_page => 16
)

要回答你的问题,在Rails 2.x中没有自然的方法来解决另一个问题。我会这样做:

conditions = ["people_specialties.people_type_id = ? AND (people_postcodes.postcode_id = ? OR people_states.state_id = ?)", self.people_type_id, postcodeid.id, stateid]

if params[:nationality]
  conditions.first += " and nationality = ?"
  conditions.push params[:nationality]
end

people = People.paginate(
  :all,
  :include => [:people_postcodes, :people_specialties, :people_states],
  :conditions => conditions, 
  :page => page, 
  :per_page => 16
)

在上面的示例中,我假设国籍作为参数传入,但根据需要进行调整。我创建了原始条件数组,然后追加第一个元素(实际条件字符串)并在数组末尾添加一个元素:国籍值。

我希望这有帮助!