开发者

Rails 3: convert session[:params] to correct activerecord query

I have two models, Foo and Bar, with same attributes, and I'm 'caching' user "search params" into a session variable, that ends into something like this:

session[:search_params] => {"price"=>"15.0", "air_conditioner"=>"0", "fireplace"=>"0", "number_of_rooms"=>"1", "balcony"=>"0"} 

I'd like to search both Foo and Bar for entries that match this 开发者_运维百科query.

For now, I'm doing:

@foo = Foo.new(session[:search_params])
search_attributes = @foo.attributes
search_attributes.delete 'id'
search_attributes.delete 'created_at'
search_attributes.delete 'updated_at'
@results = Foo.where(search_attributes)
@results += Bar.where(search_attributes)

that is REALLY UGLY.

Could anyone tell me a better/the correct way?

Thanks in advance.

EDIT

Also, some params in the session[:search_params] that are "0", are actually 'false' on the database (booleans) (filled by checkboxes), so I have to do some "conversion" into this fields so that the query is done correctly, i.e., getting for example air_conditioner => 'false' instead of air_conditioner => '0'.


I wouldn't follow that path if I were you. I would go with a solution like https://github.com/ernie/meta_search


You can use Dynamic Attribute-Based Finders: api.

So

@results = Foo.find_by_price_and_air_conditioner_and_fireplace_and_number_of_rooms_and_balcony(session[:search_params])

Also, you won't have to delete the extraneous information from session.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜