[英]Calling Rails model from another model
从另一个模型调用Rails模型是否被视为最佳实践? (下面的代码):
#models/user.rb
def get_pending_requests(user_id)
Friend.where("friend_id = ? AND approved = ?", user_id, false)
end
我发现这样做很难执行RSpec / FactoryGirl测试,而不是从Controller内部执行这些操作。
我可能会建议使用其他方法吗? 假设您的模型是这样设置的:
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
因此,您创建了一个称为挂起在朋友上的范围。 然后,您可以在您的朋友关系上使用该范围。 我发现这是一种更标准的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.