-1

I have retrieved some records based on condition in a hash - @special_products. Now I want to pass the hash to a non-restful action(:special)/ of the same controller so that I can view the products.

I've tried this but how can link_to pass hash and how should the value be retrieved in action: special? which is in the same products_controller?Many thanks.

products_controller.rb

  def show
   @special_products = Product.by_company
  end

show.html.erb

<%= link_to "Special Products", special_path(:anchor => "#{@special_products}") %>
Means
  • 322
  • 2
  • 4
  • 16

1 Answers1

1
  1. If you're hitting the show action of the Products controller, you should be showing a product.

  2. If you want to show a product in a special way, use the same show action, but render a different view for it.

    def show
      @product = Product.find(params[:id])
      render @product.special? ? 'special_show' : 'show'
    end
    
  3. If you want to list some products in a different way (a filtered collection), you want to use an index. E.g. the products#index action.

    def index
      @products = Products.not_special
      @special_products = Products.way_special
    end
    
    # app/views/products/index.html.erb
    Special Products:
    <%= @special_products.pluck(:name).to_sentence %>
    
  4. Finally, note that the parameters you pass to link_to end up in the linked URL, which means that your example link_to is going to render something like #<Array []> in the href attribute.

coreyward
  • 77,547
  • 20
  • 137
  • 166
  • Considering point(2) even if I render special_show.html.erb, I still donot have the list of records in hash. basically, I'm viewing 1 product in show and there's a link below that says "View other products from this company" so even after rendering 'special-show' I have lost id of current product so as to display other products of that same company. I'm not sure if link_to can help. Now regarding point (3) @special_products contains all selected records so to_sentence will display comma-separated....not sure, if I'm understanding differently. – Means Mar 07 '17 at 18:06
  • @Means I would have happily answered in a way that met your needs if you had explained what you were trying to do in your original question. You didn't, so I couldn't possibly have known. Please ask a new question. – coreyward Mar 07 '17 at 18:39
  • I'm actually new to rails and apologies, I couldnot make it clear. Here's another question-http://stackoverflow.com/questions/42656720/rails-link-to-pass-id-from-show-to-another-controller-action. thanks if you can give me some idea. – Means Mar 07 '17 at 19:31