简体   繁体   English

在Rails中抽象ActiveRecord模型查询的最佳实践?

[英]Best Practice to abstract ActiveRecord model queries in Rails?

I'd like to extract out logic from the controllers to somewhere that it can be more DRY. 我想从控制器中提取逻辑到更干燥的地方。 What's the best way of handling something like the following in Rails? 在Rails中处理类似以下内容的最佳方法是什么?

For instance, as opposed to having the query in the controllers, I could place it in the model: 例如,与将查询放入控制器不同,我可以将其放入模型中:

class SmoothieBlender < ActiveRecord::Base
   belongs_to :user

   def self.get_blenders_for_user(user)
      self.where(["user_id = ?", user.id])
   end
end

Or would it be better to create a module as a service layer and include that in each model that uses it? 还是将模块创建为服务层并将其包含在每个使用该模块的模型中会更好?

module BlenderUser
   def get_blenders_for_user(user)
      SmoothieBlender.where(["user_id = ?", user.id])
   end
end

class SmoothieBlender < ActiveRecord::Base
   include BlenderUser
   belongs_to :user
end

class User < ActiveRecord::Base
   include BlenderUser
   has_many :smoothie_blenders
end

Or just make it a full blown service class that's accessible from the User and Blender controller? 还是只是使其成为可从用户和Blender控制器访问的完整服务类? Where would you put this class? 您将把这节课放在哪里?

class BlenderService 
    def self.get_blenders_for_user(user)
       SmoothieBlender.where(["user_id = ?", user.id])
    end
end

I'm new to Ruby and Rails, so if this is a silly question/syntax is incorrect, forgive me. 我是Ruby和Rails的新手,所以如果这是一个愚蠢的问题/语法不正确,请原谅我。 Thanks in advance! 提前致谢!

I'd create a named_scope (I think it's just scope in Rails 3) 我将创建一个named_scope (我认为这只是Rails 3中的scope

class SmoothieBlender < ActiveRecord::Base
   belongs_to :user

   scope :for_user, lambda { |user_id|
      where("user_id = ?", user_id)
   }  
end

This way you can call 这样你可以打电话

SmoothieBlender.for_user(user.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM