How to use arguments with before filter with other options

How to use arguments with before filter with other options

Lets suppose you have a method in the application controller "find_instance" that you wanted to use as before filter with an added argument "category" .So use the below mentioned code.
before_filter { |c| c.find_instance 'category' }    
If you waned to add more options to your before filter do something like this.

before_filter(:except=>[:index,:new,:create]) { |c| c.find_instance 'category' }
And then in the application controller you do something like this

def find_instance(obj)
  instance = obj.camelize.constantize.find(params[:id])
  instance_variable_set("@#{obj}",instance) 
end

It will give you @category as an instance variable which will become
@category = Category.find(params[:id])



Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Interview Question on Ruby on Rails