开发者

Rails Newbie: Appending conditions in activerecord?

开发者 https://www.devze.com 2023-01-27 22:56 出处:网络
I have a form which is used to filter queries. Some of the form attributes are optional; I\'m just wondering how to append them as acti开发者_StackOverflow社区verecord conditions if (and only if) they

I have a form which is used to filter queries. Some of the form attributes are optional; I'm just wondering how to append them as acti开发者_StackOverflow社区verecord conditions if (and only if) they have a set value?

There's a fair few of them, so I'd rather not make a separate query for each pattern of potential values. Any suggestions?

To give a specific example:

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
)

How would I best go about creating an extra condition (say 'nationality') only if the optional 'nationality' attribute is populated?


First off, your conditions are a little insecure. You're doing basic ruby text substitution, which will let site users inject whatever malicious sql they want. Instead, format it like this:

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
)

To answer your question, there's no natural way to tack on another condition in Rails 2.x. I would do this:

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
)

In the example above, I'm assuming nationality is passed in as a parameter, but adjust as needed. I create the original conditions array, then append the first element (the actual condition string) and add one more element to the end of the array: the nationality value.

I hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号