如何神奇地为 Active Record 范围提供参数?

发布于 2024-10-31 23:07:18 字数 749 浏览 7 评论 0原文

我不确定这是否可能,但让我们看看你们中是否有人能提出解决方案。这或多或少与可读性方面的代码质量有关,而不是实际问题,因为我已经有了解决方案。我有一个友谊模型和一个用户模型。 友谊模型用于对两个用户之间的友谊进行建模:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

始终不够爱げ你 2024-11-07 23:07:18

我认为如果你把争论撤掉的话,这应该会起作用。像这样调用用户对象的挂起应该已经将友谊范围扩展到适当的用户。像这样定义方法:

def self.pending
  where(:status => 'pending')
end

并调用:

a_user.friendships.pending

如果您不确定生成的查询是否正常工作,请检查日志。

如果您仍然想通过传递参数来调用它,我会将该方法命名为 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:

def self.pending
  where(:status => 'pending')
end

And call:

a_user.friendships.pending

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文