可以加入Rails Action Text模型

时间:2019-05-11 07:12:06

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

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

工作模型(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”的关联;也许您拼错了?

在搜索“高和低”时,我找不到此查询级别的任何文档。我还没有尝试过scope mentioned here

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我使用了内部联接

模型关系为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}%") }

答案 2 :(得分:0)

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_text,可以添加has_many rich_texts关系。

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