0

我的书中有一个使用 pg_search 的模型,在搜索中我希望能够通过用户名搜索书籍。在我的 book.rb 模型中,我有以下内容:

    include PgSearch
    pg_search_scope :search, :against => [:title, :age, :story_types, :slug, :synopsis, :body, :user],
    associated_against: {
      user: [:name]
    },
    using: { tsearch:{ dictionary: "english" } }

    belongs_to :user
    belongs_to :gallery
    has_many :stories
    has_many :images
    has_many :reviews

    has_and_belongs_to_many :schools, join_table: "books_schools"

    accepts_nested_attributes_for :user
    accepts_nested_attributes_for :gallery, :allow_destroy => true
    accepts_nested_attributes_for :schools, :allow_destroy => true, :reject_if => :find_school
    accepts_nested_attributes_for :images, :allow_destroy => true


    def self.text_search(query)
      if query.present?
        where("title @@ :q or synopsis @@ :q or age @@ :q", q: query)
      else
        scoped
      end
    end

上面的代码适用于我在书中的任何内容,但我需要做的是找到与该书关联的用户名。我的架构我将 user_id 附加到 books 表,我可以在我的视图和模型中使用以下内容获取该书的用户详细信息,@book_author = User.where("id = '#{@book.user_id}'")然后获取我刚刚做的名称<%= book.user.name %>我知道有些人可能会说这很奇怪,但方式书被保存了,这对我来说是合乎逻辑的。

任何人都可以尝试帮助我开始寻找合适的地方来实现这一点。我相信它非常简单,但很难让我明白。

干杯

4

1 回答 1

-2

使用委托http://apidock.com/rails/Module/delegate 在 book.rb 添加以下行

delegate :name, :to => :user, ;prefix => true

并在视图中执行以下操作 <%= @book.user_name %>。@book 是 Book 实例

即使您不想使用委托,您也可以简单地执行以下操作 <%= @book.user.name %>

如果您提交控制器并查看代码以获得更多帮助,那就太好了。

于 2015-05-19T21:08:50.030 回答