【问题标题】:good syntax for ruby scoperuby 范围的良好语法
【发布时间】:2014-09-09 16:39:17
【问题描述】:

我只是想知道是否有办法做到这一点:

我希望我的用户类有一个“受邀”方法来创建一个用户列表,他们的 refer_code 等于 self.confirmation_token

我尝试了很多东西,最后一件事几乎是好的我知道,但是我有一个语法错误......

scope :invited, -> {|u| where("referral_code = ?", confirmation_token)}

ofc 我的意思是我想迭代数据库中的每个用户 (|u|)

【问题讨论】:

  • 试试这个scope :invited, -> {where("referral_code = confirmation_token")}

标签: ruby-on-rails ruby scope named-scope


【解决方案1】:

你可以写:

scope :invited, ->(token) { where("referral_code = ?", token) }

然后:User.ivited(some_token),但如果您需要具有相同 referral_codeconfirmation_token 字段的用户,您可以编写:

scope :invited, -> { where "referral_code = confirmation_token" }



根据您的评论(I need users who have the same referral_code than the confirmation_token of the user caller of the method invited),您可以写:

def invited
  where "referral_code = ?", confirmation_token
end

然后:User.last.invited

【讨论】:

猜你喜欢
  • 2017-12-22
  • 2012-03-21
  • 2021-12-31
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
相关资源
最近更新 更多