How do I avoid nil with a dynamic finder when an attribute comes as nil?
link_to 'articles', articles_path, :attr1 => 'foo', :attr2 =>开发者_运维百科 'bar'
And in the controller:
Article.find_all_by_attr1_and_attr2(params[:attr1], params[:attr2])
However if the controller receives only [:attr1]
I get a nil.
Dynamic finders may not be the right way to go if some of finders aren't actually present. In this case, you're probably better off using Article.find(:all, :conditions => {})
on Rails 2 and Article.where()
on Rails 3.
Here's a method I came up with for another question a while back:
conditions = [:attr1, :attr2].inject({}) do |hsh, field|
hsh[field] = params[field] if params[field] && params[field].present?
hsh
end
# Rails 2
@articles = Article.find(:all, :conditions => conditions)
# Rails 3
@articles = Article.where(conditions)
In the above case, you'd loop over all fields in the array, and add each one of them to the resulting hash if it's in and not empty in params
. Then, you pass the hash to the finder, and everything's fine and dandy.
精彩评论