I have managed to produce a series of three buttons on an index page enabling a user to identify a subset of the objects in a database - button 1 - type = "new", button 2 - type = "used", button 3 - no restriction i.e. can be new or used.
Currently index.html.erb contains:
<%= link_to "New", :controller => params[:controller], :action => params[:action], :product_type => 'New' %>
<%= link_to "Used", :controller => params[:controller], :action => params[:action], :product_type => 'Used' %>
<%= link_to "Don't Restrict", :controller => params[:controller], :action => params[:action], :product_type => nil %>
Within product.rb i have:
scope :by_product_type, lambda{|product_type| where(:product_type => product_type) unless product_type.nil? }
Finally I have productfinder_controller:
before_filter :load_grips, :only => [:index, :bybrand, :bycolour, :byprice]
protected
def load_products
if params[:product_type]
@productssmatchingtype = Product.by_product_type(params[:product_type])
else
@productsmatchingtype = Product
end
end
The above code works exactly as I hoped, loading all items initially and restricting them if Button 1 or Button 2 is pressed.
I would also like to have similar functionality on 3 other pages within the Productfindercontroller, namely byprice, bybrand and bycolour. I have put the same code as provided above in each of these 3 other .html.erb files and again things seem to be behaving...
EXCEPT - When a new page is loaded the default is that all the products are shown, i.e. it has not remembered what button the user pressed on the previous page. Is it possible to store the information regarding the button pressed somewhere which is accessible to all the pages in the controller? Similarly / Alternatively, is it possible to define @productsmatchingtype (in productfinder_controller) in such a way that it is accessible to all the pages and doesn't need to start from scratch again?
You cannot remember variables beetwen requests. However you can store product_type in session:
def load_products
#get product_type from session if it is blank
params[:product_type] ||= session[:product_type]
#save product_type to session for future requests
session[:product_type] = params[:product_type]
if params[:product_type]
@productssmatchingtype = Product.by_product_type(params[:product_type])
else
@productsmatchingtype = Product
end
end
That should do the job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With