【问题标题】:Can I get search results on pg_search from a user_id?我可以从 user_id 获取 pg_search 的搜索结果吗?
【发布时间】:2015-05-19 20:12:41
【问题描述】:

我的书中有一个使用 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 %> 我知道有些人可能会说这很奇怪,但保存书籍的方式对我来说是合乎逻辑的。

任何人都可以尝试帮助我开始寻找正确的地方以使其工作。我相信它非常简单,但很难让我明白。

干杯

【问题讨论】:

    标签: ruby-on-rails ruby postgresql ruby-on-rails-4 pg-search


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 这个可以插入pg_search吗?
    • 对不起,我不知道具体的 pg_search。
    • 那么你为什么要添加一个与上面提出的问题完全无关的答案......?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2015-10-09
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多