문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top