2

从另一个模型调用 Rails 模型是否被认为是最佳实践?(下面的代码):

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

我发现执行 RSpec/FactoryGirl 测试这样做有点尴尬,而不是在 Controller 中执行这些操作。

4

1 回答 1

5

我可以建议一种不同的方法吗?假设您的模型设置如下:

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

因此,您创建了一个名为pending onfriend 的范围。然后你可以在你的朋友关系上使用这个范围。我发现这是一种更标准的方法。

于 2013-04-21T00:14:55.413 回答