【问题标题】:Possible to join Rails Action Text Model可以加入 Rails 动作文本模型
【发布时间】:2019-05-11 07:12:05
【问题描述】:

使用 Rails 6 rc1,我正在对名为“Job”的模型进行查询。

工作模型(job.rb):

has_rich_text :description
belongs_to :company, dependent: :destroy, required: false

def self.search(query)  
  joins(:company, :description)
  .where.not(has_ended: true)
  .where("jobs.title ILIKE ?", query)
  .where("jobs.description ILIKE ?", query)
  .where("companies.name ~* ?", "^#{query}") # https://www.postgresql.org/docs/8.3/functions-matching.html
end

这正是我所拥有的。到目前为止,我的问题是包含has_rich_text。在 rails 控制台Job.joins(:description) 中复制时出现的错误:

ActiveRecord::AssociationNotFoundError(在 Job 上找不到名为“description”的关联;也许你拼错了?

在搜索“hight and low”时,我找不到有关此级别查询的任何文档。我没试过scopementioned here

【问题讨论】:

  • 如果description 是一个你不能加入的属性。您只能加入表格。从joins(:company, :description) 中删除:description
  • 嗨。正确的。但是....如何通过查询访问操作文本?

标签: ruby-on-rails ruby-on-rails-6


【解决方案1】:

事实证明你可以!我已经在我用过的Rails Github page 上发布了方法,但需要知道是否有更好的方法。

【讨论】:

  • "joins(:rich_title) # 这永远行不通,这是可以理解的" 你离那里很近。应该是 joins(:rich_text_rich_title)
【解决方案2】:

我使用了内连接

模型关系是 1:1 和文章:action_text_rich_text

在文章模型中

scope :search, -> (name) { joins("INNER JOIN action_text_rich_texts ON action_text_rich_texts.record_id = articles.id").where("action_text_rich_texts.body LIKE ? or articles.title like ?", "%#{name}%", "%#{name}%") }

【讨论】:

    【解决方案3】:

    实际上已经有一个has_rich_text方法定义的has_one关系

    github.com/rails/.../actiontext/lib/action_text/attribute.rb Line 37

    # name on the next two lines is a reference to what you called your rich_text.
    has_one :"rich_text_#{name}",
      -> { where(name: name) },
      class_name: "ActionText::RichText",
      as: :record,
      inverse_of: :record,
      autosave: true,
      dependent: :destroy
    

    所以在你的情况下,你想加入rich_text_description


    为了搜索多个rich_texts,你可以添加一个has_many rich_texts关系。

    has_many :rich_texts,
      class_name: "ActionText::RichText",
      as: :record,
      inverse_of: :record,
      autosave: true,
      dependent: :destroy
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多