开发者

Rails doing a FIND with Conditions?

开发者 https://www.devze.com 2023-01-20 06:14 出处:网络
In Rails 3, I created a Search Form that does a FIND with conditions in the Models file. @projects = find(:all,

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开发者_如何学JAVA, to not error but return everything.

Suggestions? Thanks!


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?}


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


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

0

精彩评论

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

关注公众号