link to association rails没有这样的专栏

时间:2015-10-21 17:00:44

标签: ruby-on-rails ruby associations

我正在尝试在Rails中设置搜索功能。我有一张叫做文件的桌子。我可以搜索主体和正文中的文字。我遇到问题的地方是尝试搜索关联表中的字段。我有一张叫做作家的桌子。我希望能够在作者字段中输入名称并返回与该作者匹配的文档。

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

主题和身体都很好。我已经尝试了作者行上的各种变化而没有运气。我的文档模型的模式如下所示,author_id链接到authors表,文档和作者之间的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?

现在,我收到如下错误

  

显示C:/Users/cmendla/RubymineProjects/Rl2/app/views/searches/show.html.erb第9行引发:   未定义的方法author' for #<Document::ActiveRecord_Relation:0xa20a0f8> Rails.root: C:/Users/cmendla/RubymineProjects/Rl2 Application Trace | Framework Trace | Full Trace app/models/search.rb:12:in search_documents'   app / views / searching / show.html.erb:9:in`_app_views_searches_show_html_erb__631448441_64839156'

THX

1 个答案:

答案 0 :(得分:2)

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

这假定作者的姓名存储在name表格中名为authors的列中,而Document模型的belongs_to :author列表。{/ p>