【问题标题】:Need correct wording for scope method seeking specific wording in the object范围方法需要正确的措辞在对象中寻求特定措辞
【发布时间】:2019-11-02 13:32:43
【问题描述】:

我想不出这个范围方法的正确措辞。任务是创建一个范围方法,指定请求(有注释)以仅显示注释中带有单词“kids”的请求。我似乎无法找到正确的措辞来使它起作用

我试过scope :requests_with_kids_in_note, -> { where('note').includes(text: "kids")}

scope :requests_with_kids_in_note, -> { select('note').where('note').includes(text: "kids")}

错误消息没有帮助

【问题讨论】:

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


    【解决方案1】:

    您可以通过范围很容易地做到这一点,但您应该以不同的方式格式化 where 子句。另外我建议让它更通用:

    scope :note_contains, -> (word) { where('note LIKE %?%', word) }
    

    并像这样使用它:

    Model.note_contains('kids')
    

    【讨论】:

    • 嘿,谢谢!这正是我想要的
    • 很高兴为您提供帮助!随时:)
    【解决方案2】:

    您可以使用Arel 来编写该查询。

    假设您有一个具有has_many :notes 关联的Request,您可以这样编写范围:

    class Request < ApplicationRecord
      has_many :notes
    
      scope :with_kids_in_note, -> {
        joins(:notes).where(Note.arel_table[:content].matches('%kids%'))
      }
    end
    
    class Note < ApplicationRecord
      # In this model, i'm assuming that "content" is the column
      # in which you have to find the word "kids".
      belongs_to :request
    end
    

    【讨论】:

    • 很好,这可能是一个 1:many 关系......我怀疑这个问题是否真的如此。但这取决于 TS 来决定。
    • 谢谢。注意实际上是一个参数,这也很有教育意义。谢谢
    猜你喜欢
    • 2020-02-17
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多