Reputation: 171321
I added @sort_by
attribute to my controller, and initialized it's value like this:
class ProductsController < ApplicationController
def initialize
@sort_by = :shop_brand
end
...
end
This caused the default application layout not to be used.
Why ?
What is the right way to add an attribute to a controller and initialize it ?
Upvotes: 0
Views: 381
Reputation: 7801
Overriding the constructor is probably a bad idea (as you have found). You should use a before_filter
:
class ProductsController < ApplicationController
before_filter :set_defaults
...
private
def set_defaults
@sort_by = :shop_brand
end
end
However, it sounds like you want to keep state. The easiest is to store in the user's session which will automatically persist per user until they close the browser:
def set_defaults
session[:sort_by] ||= :shop_brand
end
The other option would be to pass the current sort_by value in the URL. This is harder to implement though as you'll need to ensure each link or form copies the value over to the next request. The advantage of this however is the user could have multiple tabs open with different orderings and any bookmarked link would restore the same ordering next time. This is the approach that things like search engines would use.
Upvotes: 6