Tam*_*iev 7 ruby activerecord ruby-on-rails ruby-on-rails-3
我需要根据params数据添加条件.
@users = User.where('id', params[:id]) unless params[:id].nil?
@users = User.where('email', params[:email]) unless params[:email].nil?
@users = User.limit(10)
Run Code Online (Sandbox Code Playgroud)
但由于某种原因它不起作用.谢谢
Par*_*ert 23
你的每个语句都在替换@users变量,并且当ActiveRecord懒惰地评估每个语句时,前两个语句永远不会被调用.
如果您想维护三个单独的查询并以这种方式构建,您可以执行以下操作:
@users = User.limit(10)
@users = @users.where('id', params[:id]) if params[:id]
@users = @users.where('email', params[:email]) if params[:email]
Run Code Online (Sandbox Code Playgroud)
它不是最漂亮的,但它会起作用.但是,我建议将其保留为单个方法调用并在模型中定义它.
# In the model
def self.by_id_and_email(id, email)
users = limit(10)
users = users.where('id', id) if id.present?
users = users.where('email', email) if email.present?
users
end
# In the controller / out of the model
User.by_id_and_email(params[:id], params[:email])
Run Code Online (Sandbox Code Playgroud)
这样,您可以再次使用该方法,对其进行优化,并针对它编写速度(ier)测试.
如果未提供param,您可以向模型中添加不执行任何操作的范围,例如(范围调用仅返回当前范围)
# in the model
def self.by_id(id)
return scoped unless id.present?
where(:id => id)
end
def self.by_email(email)
return scoped unless email.present?
where(:email => email)
end
# in the controller
User.by_id(params[:id]).by_email(params[:email])
Run Code Online (Sandbox Code Playgroud)