ruby-on-railsruby-on-rails-5pg-search

Map name of model object to a pg_search query param in Rails 5.1


I have an album model, that has one 'cover_image' and has_many 'images'. I also have a product model. I am using pg_search to filter my products.

Independently, they both work flawlessly. What I would like to do is show an albums cover_image based on the pg_search filter param.

For example: If I had a filter param called "limestone", I would create an album called "limestone" and when a user filters the page by limestone, they would get the product results along with the matching cover_image.

product_controller - this works for filtering

  def index
    @products = if params[:query]
                  Product.search_for(params[:query])
                else
                  Product.order(:name)
                end
  end 

product_controller - this breaks the page I tried this in an attempt to keep it simple and filter the image in the model

  def index
    @products = if params[:query]
                  Product.search_for(params[:query])
                  *@albums = Album.where(name:(params[:query]))*
                else
                  Product.order(:name)
                end
  end

products/index.html.erb Then I would just call the album as normal.

...
<% @albums.each do |a| %>
    <%= image_tag("#{a.cover_image_url(:original)}") %>
<% end %>
...

Solution

  • The problem is that you're assigning @albums to @products. This is in effect what you're doing:

    @products = @albums = Album.where(name: (params[:query]))

    because the if statement is returning @albums. So this should work (assuming that the rest of your logic is correct):

    def index
      @products = if params[:query]
                    @albums = Album.where(name: params[:query])
                    Product.search_for(params[:query])
                  else
                    Product.order(:name)
                  end
    end
    

    However, I would not assign @albums where you are doing so right now. I think this is clearer thus slightly better:

    def index
      if params[:query]
        @products = Product.search_for(params[:query])
        @albums   = Album.where(name: params[:query])
      else
        @products = Product.order(:name)
        @albums   = []
      end
    end