AnApprentice
AnApprentice

Reputation: 111080

Rails doing a FIND with Conditions?

In Rails 3, I created a Search Form that does a FIND with conditions in the Models file.

  @projects = find(:all,
                :select => 'projects.*',
                :conditions => ['name = ?', search_name]
                ).first

This works great if a name is provided in the searchform (search_name). Problem is if search_name is blank, Rails Errors (can't say I blame it)...

What is the smart way to handle this situation? I'd like, if search_name is blank, to not error but return everything.

Suggestions? Thanks!

Upvotes: 1

Views: 352

Answers (3)

Yannis
Yannis

Reputation: 5426

You can create a scope to handle this. In your Project model, add something like:

scope :search_by(name), lambda{|name| first.where(:name => name) unless name.blank?}

then in your controller, simply call:

Project.search_by(params[:search])

EDIT:

If you need to serach for multiple fields you can adapt the scope:

scope :search_by(name), lambda{|name| first.includes(:owner).where("projects.name LIKE ? OR owners.name LIKE ?", name, name) unless name.blank?}

Upvotes: 5

Abel Tamayo
Abel Tamayo

Reputation: 165

The cleanest way is using lazy loading with the new ActiveRecord functionalities like this:

@projects = Project.order(:name) @projects = @projects.where(:name => search_name) if search_name

You can add as many conditions as you like this way. They won't be executed until you need the results anyway (with @projects.all or @projects.each, etc...)

Upvotes: 1

bensie
bensie

Reputation: 5403

if search_name.blank?
  @projects = Project.order(:name)
else
  @projects = Project.where(:name => search_name)
end

Upvotes: 3

Related Questions