如何神奇地为 Active Record 范围提供参数?
我不确定这是否可能,但让我们看看你们中是否有人能提出解决方案。这或多或少与可读性方面的代码质量有关,而不是实际问题,因为我已经有了解决方案。我有一个友谊模型和一个用户模型。 友谊模型用于对两个用户之间的友谊进行建模:
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!
I'm not sure this is even possible, but let's see if one of you comes up with a solution. This is more or less about code quality in terms of readability and not an actual problem because I already have a solution. I have a friendship model and a user model. The friendship model is used to model friendships between two users:
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
Is it somehow possible to call the requested, pending or accepted scope through
the user model without providing an argument?
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为如果你把争论撤掉的话,这应该会起作用。像这样调用用户对象的挂起应该已经将友谊范围扩展到适当的用户。像这样定义方法:
并调用:
如果您不确定生成的查询是否正常工作,请检查日志。
如果您仍然想通过传递参数来调用它,我会将该方法命名为
Friendship.pending_for(user)
。I think this should work if you take the argument off. Calling pending off of the user object like this should already scope friendships to the appropriate user. Define the method like this:
And call:
Check the logs for the generated query if you're not sure it's working.
If you still want to call it by passing an argument I'd name that method
Friendship.pending_for(user)
.