How to Pass Params to Named Scope in Rails
Hi guys :)
In my previous post create named scope in rails, I told you about named scope in rails, what excess of named scope,how to create and how to use it. Now i will tell you, how to pass params to named scope in rails. For example, we will search users by user_name, first_name, last_name, email and city. Most of us, will create in the controller like this :
|
1
2
3
4
5
6
|
class UsersController < ApplicationController def search @users = User.where(["user_name LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR city LIKE ?", "%#{params[:keyword]}%", "%#{params[:keyword]}%", "%#{params[:keyword]}%", "%#{params[:keyword]}%", "%#{params[:keyword]}%"]) endend |
That’s will work correctly, but that’s not recomended by rails development. I think the best way to do it is to create named scope and pass the params to named scope. Please look below, how to pass params to named scope in rails.
In user model :
|
1
2
3
4
5
|
class User < ActiveRecord scope :search, lambda{|keyword| where(["user_name LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR city LIKE ?", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%", "%#{keyword}%"])}end |
In user controller :
|
1
2
3
4
5
|
class UsersController < ApplicationController def search @users = User.search(params[:keyword]) endend |
| Source : http://whatisrubyonrails.com/how-to-pass-params-to-named-scope-in-rails |