2017-04-21 95 views
0

我创建的模型的方法基于以下Rails的最佳实践模型

SELECT TOP 1 Column1 
FROM vSomeView 
WHERE vSomeView.ColumnID = @column_id 
AND Column2 = 'Abc' 
AND Column3 = 'Def' 

SQL查询我创建了这个方法,但想知道什么是最好的做法在SQL查询创建方法在哪里有条件。应该在哪些条件在范围内或者他们应该在方法中?

class Abc 
    class Def < ActiveRecord::Base 

self.table_name = 'vSomeView' 

scope :column2scope, -> { where(column2: 'Abc') } 
scope :column3scope, -> { where(column3: 'Def') } 

def self.some_method(column_id) 
    Def 
    .select('vSomeView.column1') 
    .where("vSomeView.ColumnID = #{column_id}") 
    .first 
    end 
    end 
end 

回答

0

这取决于如果像的范围:

scope :column2scope, -> { where(column2: 'Abc') } 

可以独立使用。即调用Klass.column2scope获取所有匹配记录是否有用?一个真实的例子会是这样的:

scope :expired, -> { where('created_at < ?', 1.year.ago) } 

现在我们可以调用Product.expired来查找旧产品。或者将其结合到查询Product.expired.where(department :: food)中。

如果查询始终是整件事情在一起,你可能只是把它放在一起的方法。