Accessing one controller variable in another controller in Rails

后端 未结 3 1999
情深已故
情深已故 2021-02-06 09:45

I have a C programming background and I am learning Ruby/Rails for a side project. Currently I am struggling to understand how the scoping of variables works. Here is an example

3条回答
  •  面向向阳花
    2021-02-06 10:11

    You have to initialize @current_user on each request, not only after the user logs in. Controller instance variables do not persist across requests.

    Here's a common way to do this:

    1. Store the user ID in the session.
    2. Create a "before" filter in ApplicationController that retrieves the user ID from the session and initializes the instance variable.

提交回复
热议问题