【问题标题】:Rails active record model method chaining and getting the initial inputRails 活动记录模型方法链接并获取初始输入
【发布时间】:2021-06-16 14:37:00
【问题描述】:

感觉应该很简单,但不确定语法是否正确。这是我在玩和学习,所以这并不紧迫。

我想在模型上编写一个自定义方法,该方法执行一个动作并从方法链中获取输入,而不是要求您在方法调用中设置输入参数。

鉴于我们有以下简单的类;

class Comment < ApplicationRecord

  scope :for_user, ->(u) { where(user_id: u.id) }

  def self.do_thing
    # How do I get the results from the chain?
    # For example how do I get the IDs?
  end
end

所以我希望能够做到这一点;

Comments.for_user(current_user).do_thing

并让do_thing 方法知道Comments.for_user(current_user) 的结果是什么

现在显然我可以让 do_thing 有方法参数,然后走那条路,但我正在玩和学习方法链..

感谢您的意见。

【问题讨论】:

  • 你写的东西已经可以工作了,不是吗?你到底想让do_thing 做什么?尝试定义方法,看看它是否按预期工作。
  • 很难就如何编写代码给出建议,因为您提供给我们的唯一信息是没有所需行为的空白方法:)
  • 你是对的..对不起..在做事中,我怎么知道和操纵输入?所以前两个的结果是一个活动记录关系。假设我只想获取结果的 ID。
  • 如果有帮助,您可以认为scope :for_user, -&gt;(u) ... 与定义def self.for_user(u) ... 几乎相同
  • Make do thing 只是打印出发送给它的结果的 ID.. 例如。对不起,我没有在原帖中给出一个例子。我会编辑它

标签: ruby-on-rails rails-activerecord method-chaining


【解决方案1】:
Class Comment < ApplicationRecord

  scope :for_user, ->(u) { where(user_id: u.id) }

  def self.do_thing
    # How do I get the results from the chain?
    # For example how do I get the IDs?
    self.ids
  end
end

使用self。作用域的工作方式是它们返回一个 ActiveRecord::Relation 对象,该对象的代理方法回调模型类。

虽然在这种情况下,该方法实际上会中断链接,因为它返回一个数组而不是 self 或 ActiveRecord::Relation

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2016-04-13
    • 2023-04-03
    相关资源
    最近更新 更多