我不确定这是否可行,但让我们看看你们中有没有人想出一个解决方案。这或多或少与可读性方面的代码质量有关,而不是实际问题,因为我已经有了解决方案。我有一个友谊模型和一个用户模型。 友谊模型用于模拟两个用户之间的友谊:
class Friendship
def self.requested(user)
where(:user_id => user).where(:status => 'requested')
end
def self.pending(user)
where(:user_id => user).where(:status => 'pending')
end
def self.accepted(user)
where(:user_id => user).where(:status => 'accepted')
end
# ...
end
class User
has_many :friendships
# ...
end
是否可以通过某种方式调用请求的、待定的或接受的范围 不提供参数的用户模型?
a_user.friendships.pending # this does not work, is there a way to get it working?
a_user.friendships.pending(a_user) # works of course!
最佳答案
我认为如果您取消争论,这应该会起作用。像这样调用用户对象的挂起应该已经将友谊范围限定到适当的用户。像这样定义方法:
def self.pending
where(:status => 'pending')
end
然后调用:
a_user.friendships.pending
如果您不确定生成的查询是否正常工作,请检查日志。
如果您仍想通过传递参数来调用它,我会将该方法命名为 Friendship.pending_for(user)
。
关于ruby - 如何神奇地为 Active Record 范围提供参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5627461/