Rails中scopes的几种使用方法

来源:互联网 发布:淘宝运营主要做什么 编辑:程序博客网 时间:2024/06/06 06:49

不传参数使用scope方法
class User < ActiveRecord::Base
scope :finduser, {where(status: 'username')}
scope :has_content, {joins(:comment).where("comments.content is not null")}
end



传参数使用scope方法

class User < ActiveRecord::Base
scope :finduser, ->(username){ where(username: username) }
scope :has_content, ->(content){joins(:comment).where('comments.content = ?', content)}
end



class User < ActiveRecord::Base
scope :finduser, Proc.new { |username| where(username: username) }
scope :has_content, Proc.new{joins(:comment).where('comments.content = ?', content)}
end



class User < ActiveRecord::Base
scope :finduser, lambda { |username| where(username: username) }
scope :has_content, lambda{joins(:comment).where('comments.content = ?', content)}
end


class User < ActiveRecord::Base
def self.finduser username
where(username: username) unless username.empty?
end



def self.has_content content
lambda{joins(:comment).where('comments.content = ?', content)}
end
end


总结

当逻辑是简单的where/order这样的查询时使用scope;涉及到复杂查询时,使用类方法。
另外,当需要做一些扩展时,作为Active Record提供的一个特性,我还是推荐使用scope。






0 0
原创粉丝点击