link 关联 rails 没有这样的栏目

link to association rails No such column

我正在尝试在 Rails 中设置搜索功能。我有一个叫table的文件。我可以在 body 中搜索主题和文本。我遇到问题的地方是试图搜索关联 table 中的字段。我有一个叫 authors 的 table。我希望能够在作者字段中输入姓名,并 return 匹配该作者的文档。

class Search < ActiveRecord::Base

  has_many :documents

  def search_documents

    documents = Document.all

    documents = documents.where("subject like ?", "%#{subject}%") if subject.present?
    documents = documents.where("body like ?", "%#{text}%") if text.present?
    documents = documents.author.where("author like ?", "%#{author}%") if author.present?

    return documents
  end

end

主题和 body 工作正常。我已经尝试了 author line 上的各种变体,但没有成功。我的文档模型的架构如下所示,author_id 链接到作者 table 在文档和作者

之间的 has_many 关系
create_table "documents", force: :cascade do |t|
  t.string   "subject"
  t.text     "body"
  t.integer  "category_id"
  t.integer  "tag_id"
  t.integer  "author_id"
  t.integer  "reviewer_id"
  t.datetime "created_at",                       null: false
  t.datetime "updated_at",                       null: false
  t.string   "document_attachment_file_name"
  t.string   "document_attachment_content_type"
  t.integer  "document_attachment_file_size"
  t.datetime "document_attachment_updated_at"
  t.integer  "attached_files_id"
  t.string   "token"
end

有没有办法在

中引用作者的名字
documents.author.where("author like ?", "%#{author}%") if author.present?

现在,我收到如下错误

Showing C:/Users/cmendla/RubymineProjects/Rl2/app/views/searches/show.html.erb where line #9 raised: undefined method author' for #<Document::ActiveRecord_Relation:0xa20a0f8> Rails.root: C:/Users/cmendla/RubymineProjects/Rl2 Application Trace | Framework Trace | Full Trace app/models/search.rb:12:insearch_documents' app/views/searches/show.html.erb:9:in `_app_views_searches_show_html_erb__631448441_64839156'

谢谢

documents.joins(:author).where("authors.name like ?", "%#{author}%") if author.present?

这假设作者的姓名存储在 authors table 中名为 name 的列中,并且 Document 模型有一个 belongs_to :author.