gpt4 book ai didi

ruby-on-rails - 使用 lambda 的事件记录中的范围 - 在 Rails 控制台中返回无方法错误

转载 作者:行者123 更新时间:2023-12-02 05:18:56 25 4
gpt4 key购买 nike

在我的用户模型类中,我定义了 2 个范围,如下所示。

  scope :condition, lambda { where('updated_at >= ?', 3.day.ago) }

scope :tardy, lambda {
joins(:timesheets).group("users.id") & Timesheet.condition
}

然后我尝试运行reload!,然后运行u =User.find 14,结果如下。

  User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 14 LIMIT 1
=> #<User id: 14, login: "janu", password: "janu", password_confirmation: nil, email: "janu@gmail.com", created_at: "2013-01-03 09:47:36", updated_at: "2013-01-03 09:47:36">

然后我运行 u.tardy.to_sql,但它返回以下错误。

NoMethodError: undefined method `tardy' for #<User:0x00000003cb5ea0>
from /home/local/rajesh.co/.rvm/gems/ruby-1.9.3-p327/gems/activemodel-3.2.9/lib/active_model/attribute_methods.rb:407:in `method_missing'
from /home/local/rajesh.co/.rvm/gems/ruby-1.9.3-p327/gems/activerecord-3.2.9/lib/active_record/attribute_methods.rb:149:in `method_missing'
from (irb):64
from /home/local/rajesh.co/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.9/lib/rails/commands/console.rb:47:in `start'
from /home/local/rajesh.co/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start'
from /home/local/rajesh.co/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.9/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

看,当我如下所示将两个作用域连接在一起时,我也会遇到同样的错误。

  scope :tardy, lambda {
joins(:timesheets).
where("timesheets.updated_at >= ?", 3.days.ago).
group("users.id")
}

你能帮我解决同样的问题吗?谢谢。

最佳答案

您不能在特定记录上调用范围。当您调用 .find 时,您将返回一条特定记录,而不是可以链接其他范围的关系/关联。

如果你想找到任何 ID 为 14 的迟到用户,你必须颠倒方法调用的顺序:

User.tardy.find(14)

仍然将无法运行.to_sql,因为您将再次拥有一条记录。如果你真的想要 SQL 返回特定的 find-by-id,你可以使用

User.tardy.where(:id => 14).to_sql

关于ruby-on-rails - 使用 lambda 的事件记录中的范围 - 在 Rails 控制台中返回无方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14190024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com