2
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.

Bob Aman
  • 32,839
  • 9
  • 71
  • 95
elkalto23
  • 267
  • 3
  • 12
  • What would you do in that case then? There's not enough information to answer this question effectively. – Ryan Bigg Jan 21 '11 at 00:05

1 Answers1

2

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.

vonconrad
  • 25,227
  • 7
  • 68
  • 69