简体   繁体   English

从另一个模型调用Rails模型

[英]Calling Rails model from another model

Is it considered a best practice to call a Rails model from another model ? 从另一个模型调用Rails模型是否被视为最佳实践? (code below) : (下面的代码):

#models/user.rb
def get_pending_requests(user_id)
  Friend.where("friend_id = ? AND approved = ?", user_id, false)
end

I find it a bit awkward to perform RSpec/FactoryGirl tests doing this, as opposed to perform these actions from within a Controller. 我发现这样做很难执行RSpec / FactoryGirl测试,而不是从Controller内部执行这些操作。

Might I suggest a different approach? 我可能会建议使用其他方法吗? Assuming that your models are setup like this: 假设您的模型是这样设置的:

class Friend < ActiveRecord::Base
  belongs_to :user

  scope :pending, -> { where(approved: false) }
end

class User < ActiveRecord::Base
  has_many :friends

  def pending_requests
    friends.pending
  end
end

So you create a scope called pending on friend. 因此,您创建了一个称为挂起在朋友上的范围。 Then you can use that scope on your friends relation. 然后,您可以在您的朋友关系上使用该范围。 I find this to be a more standard approach. 我发现这是一种更标准的方法。

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

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