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
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.
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
精彩评论