Intrepidd
Intrepidd

Reputation: 20858

How to call a before_filter with various parameters depending on the controller?

I have two controller :

class MyController < ApplicationController
  before_filter :get_model
  # Actions
end

class MyOtherController < ApplicationController
  before_filter :get_model
  # Actions
end

In my ApplicationController, I have a function that I use to get a certain model :

def get_model
  @model = Model.find(params[:model_id])
end

However, the parameter that will hold the model id is not the same for both controllers.

How can I make this work without repeating myself ?

Upvotes: 1

Views: 1388

Answers (1)

Intrepidd
Intrepidd

Reputation: 20858

before_filter can accept a Proc or a lambda as its first parameter.

Refactor your get_model function so it accepts and id :

def get_model(id)
  @model = Model.find(id)
end

Then call your before_filter with a lambda, and pass the corresponding id :

before_filter lambda { get_model(params[:whatever_id]) }

Upvotes: 1

Related Questions