开发者

A question about will_paginate's with multiple conditions

As my title, I want set multiple conditions in will_paginate, that's my model's code

class Room < ActiveRecord::Base
  belongs_to :province
  belongs_to :city
  belongs_to :region
  belongs_to :street
  belon开发者_开发知识库gs_to :estate
  def self.search(city_id, region_id, layout, page)
    conditions = []
    conditions.push("city_id = #{city_id}")
    conditions.push("region_id = #{region_id}")
    conditions.push("layout = #{layout}") if layout!=0
    paginate :per_page => 5, :page => page,
      :conditions => conditions
  end
end

invode it in controller:

@rooms = Room.search(city, region, layout, params[:page])

but..doesn't work right..It just consider the first condition.

who can give me a sample code?? Thx!


A better approach would be to use conditions like this(which is preferred in Rails)

class Room < ActiveRecord::Base
  belongs_to :province
  belongs_to :city
  belongs_to :region
  belongs_to :street
  belongs_to :estate
  def self.search(city_id, region_id, layout, page)
    conditions = {}
    conditions.merge!(:city_id => city_id)
    conditions.merge!(:region_id => region_id)
    conditions.merge!(:layout => layout) if layout!=0
    paginate :per_page => 5, :page => page,
      :conditions => conditions
  end
end

This will eliminate the risk of SQL injection.


Try this:

class Room < ActiveRecord::Base
  belongs_to :province
  belongs_to :city
  belongs_to :region
  belongs_to :street
  belongs_to :estate
  def self.search(city_id, region_id, layout, page)
    conditions = []
    conditions.push("city_id = #{city_id}")
    conditions.push("region_id = #{region_id}")
    conditions.push("layout = #{layout}") if layout!=0
    paginate :per_page => 5, :page => page,
      :conditions => conditions.join(' and ')
  end
end

This would concatenate all of your conditions with "AND".

The reason your code doesn't work is that when you use an Array for condition, the first element should be a condition with SQL params and remaining elements - are param values. For example:

Room.paginate(:conditions => ['city_id = ? and region_id = ?', city_id, region_id])

That's why it only considers the first condition.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜