Variable scope in rails controller

181 views
Skip to first unread message

Sai Ch

unread,
Nov 26, 2015, 4:52:02 PM11/26/15
to rubyonra...@googlegroups.com
Hi,

I need to access one variable in entire controller i.e it is accessible
to all actions in controller.

I had tried with session and class variable but for example

def create
document_id = get_document
@@document_id = session[:document_id] = document_id
end

def validate
if document_id == (@@document_id || session[:document_id])
true
else
false
end
end

it works some time , some time uninitialized constant error for class
variable and session token is null when I refresh the browser.

I know session variable stored in server side but when I request
multiple times it returns null value.

i am also using before filter for that task, but no use.

please suggest me.

--
Posted via http://www.ruby-forum.com/.

Colin Law

unread,
Nov 26, 2015, 5:14:43 PM11/26/15
to Ruby on Rails: Talk
If you want a variable that has to be determined once for each request
but is available in all actions then before_filter is the way to go.
If you want a variable that persists from request to request (such as
current logged in user) then the session is what you want.

Give us more detail on exactly what you are trying to achieve.

Colin

>
> please suggest me.
>
> --
> Posted via http://www.ruby-forum.com/.
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/0966b9f0c0a795189fe0c1c462218b79%40ruby-forum.com.
> For more options, visit https://groups.google.com/d/optout.

Sai Ch

unread,
Dec 3, 2015, 11:11:42 AM12/3/15
to rubyonra...@googlegroups.com
Hi,

I would like to know variable scope for variable accessibility in all
rails controller methods.

for example, I had done like below.

class app_controller

def set_vaule
@var = "12gfjdl"
end

def actions1
need display @var here
end

def action2
here also need @var value
end

end

note: I had tried with session and declare @var as class variable(@@var)
it access only first time, later if I made any request again the action
is set to nil i.e
uninitialised class variable.

Colin Law

unread,
Dec 3, 2015, 11:23:53 AM12/3/15
to Ruby on Rails: Talk
An instance variable (@...) is available in any method. Note though
that since the controller is reconstructed for each request it will
not survive between requests (so in the above you might want a
before_filter calling set_value). To have a persistent object that
survives over multiple requests (per user) then use the session.

If something is always a fixed value then use a constant.

Colin
Reply all
Reply to author
Forward
0 new messages