Search code examples
ruby-on-railsrubypostgresqlmodelpg

Rails How to use model with params in view


I want to make suggested product show up on show page I have this in my model(i am using pg)

//Product model
def self.similar(product_name)
        where("name LIKE ?", "%#{product_name}%").limit(4)
      end 

How do i use this in my views(how to pass params)


Solution

  • So I'm not sure where you are getting the 'product_name' but it sounds like you just need a variable in the controller 'Show' method.

    The easy way would be to just add something like the following into your Controllers 'Show' method;

    def show
        @similar_products = Product.where("name LIKE ?", params[:product_name]).limit(4)
    end
    

    And then in your show page just add it into the html.erb;

    <div class='container'>
        <% @similar_products.each do |product| %>
            <%= product.name %>
            <%= product.price %>
        <% end %>
    </div>