Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persistent parameter in Rails controller

is there any way to persist (preserve) parameters in Rails controller? It should be passed to every action, then to every view and every link.

Example situation: I have entity A with its controller. Besides, I have another entity B which is dependent on A. I need to access the "parent" A entity very often, so I'd like to have it still as

http://some_url/b_controller/b_action?a_entity=xyz

like image 316
Pavel S. Avatar asked Aug 03 '11 08:08

Pavel S.


2 Answers

You should be able to do everything from your controller, using a combination of before_filter and default_url_options :

class MyController < ApplicationController

  before_filter :set_a_entity

  def set_a_entity
    @a_entity = params['a_entity']
    # or @a_entity = Entity.find(params['a_entity'])
  end

  # Rails 3
  def url_options
    {:a_entity => @a_entity}.merge(super)
  end

  # Rails 2
  def default_url_options
    {:a_entity => @entity}
  end

end

This doesn't solve the problem of setting the initial value of @a_entity, but this can be done from anywhere (view, controller, etc).

If you want this parameter passed around in multiple controllers, you can replace MyController < ApplicationController with ApplicationController < ActionController::Base and it should work as well.

Hope this helps.

like image 130
Benoit Garret Avatar answered Sep 29 '22 18:09

Benoit Garret


why not put it in a session parameter then?

session["a_entity"] = "xyz"

that way you can access it in all your other controllers too until you clear it or it expires.

more info here:

http://api.rubyonrails.org/classes/ActionController/Base.html

like image 24
corroded Avatar answered Sep 29 '22 17:09

corroded