我有一个Post模型,该模型使用ActionText作为属性content
has_rich_text :content现在我有了一个简单的搜索,我想在content中搜索文本,所以我有这样的东西:
@posts = Post.joins("INNER JOIN action_text_rich_texts ON action_text_rich_texts.record_id = posts.id").where("action_text_rich_texts.content LIKE ?", "%#{search_text}%")但这会给出一个错误:
PG::UndefinedColumn: ERROR: column action_text_rich_texts.content does not exist在ActionText属性中搜索文本的正确方法是什么?
发布于 2020-01-04 01:51:45
这是rails action_text:install生成的迁移:
# This migration comes from action_text (originally 20180528164100)
class CreateActionTextTables < ActiveRecord::Migration[6.0]
def change
create_table :action_text_rich_texts do |t|
t.string :name, null: false
t.text :body, size: :long
t.references :record, null: false, polymorphic: true, index: false
t.timestamps
t.index [ :record_type, :record_id, :name ], name: "index_action_text_rich_texts_uniqueness", unique: true
end
end
end它告诉我们内容存储在action_text_rich_texts中,并使用多态关联链接到记录。
因此,您需要在连接中提供类型和id,因为可能有多个行具有相同的id,但用于不同的模型:
@posts = Post.joins("INNER JOIN action_text_rich_texts ON action_text_rich_texts.record_id = posts.id AND record_type = 'Post'")您可以通过设置关联,这样您就不必手动加入:
class Post < ApplicationRecord
has_rich_text :content
# used to query the attached ActionText directly
has_one :action_text_rich_text,
class_name: 'ActionText::RichText',
as: :record
end整个查询是这样的:
@posts = Post.joins(:action_text_rich_text)
.where("action_text_rich_texts.body LIKE ?", "%#{search_text}%")发布于 2020-02-10 00:53:45
谢谢,麦克斯,我整天都在用Ransack来解决这个问题。
所以我补充道:
has_one :action_text_rich_text,class_name:‘动作文本::RichText’,as::record
然后在我的搜索字段中使用了_or_action_text_rich_text_body_,它就像一个护身符。
https://stackoverflow.com/questions/59575397
复制相似问题