简体   繁体   中英

Can I get search results on pg_search from a user_id?

I have a model in my books that use pg_search, in the search I want to be able to search books by a user name. In my book.rb model I have this as follows:

    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

The above code works fine for anything I have in books but what I need to do is find the user name associated with that book. I my schema I have user_id attached to the books table and I can get the users details for that book with the following in my views and model @book_author = User.where("id = '#{@book.user_id}'") and then to get the name I just do <%= book.user.name %> I know some people may say this is weird but the way the books are saved it's logical for me.

Can anyone please try and help me to start looking in the right place for this to work. I am sure its pretty simple but its hard to get my head around.

Cheers

Use delegate http://apidock.com/rails/Module/delegate In book.rb add following line

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

And in views do following <%= @book.user_name % >. @book is a Book instance

Even if you don't want to use delegate you can simple do following <%= @book.user.name % >

It would be great if you submit the controller and view code for more help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM