Accessing one controller variable in another controller in Rails

后端 未结 3 1991
情深已故
情深已故 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:30

    An instance variable set in one action can't be accessed in another action. As mentioned, you will need to store the user_id in the session hash. In the controller that handles your user sign_in, you will have to do something like this:

    #in SessionsController(for example)
    
    def create
      user = User.find_by(email: params[:session][:email].downcase)
      if user && user.authenticate # logic for authentication
        session[:user_id] = user.id
        redirect_to root_path, notice: "Successful sign in."
      else
        flash.now[:error] = "Invalid email/password combination"
        render :new
      end
    end
    

    Take note of assigning the user_id to the session key :user_id in the session hash. Now, in application_helper or sessions_helper define current_user so that it's accessible to all views:

    def current_user
      User.find(session[:user_id]) if session[:user_id]
    end
    

    Now to iterate through all of a certain user's products:

    
    <% current_user.products.each do |product| %>
      
        <%= product.userid %>
        <%= product.product_name %>
        <%= product.product_link %>
    

    As long as you have a has_many :products association in User and Product model has belongs_to :user, you should be able to call all of a user's products by just doing user.products like above. Notice too that I used 'snake_case' for the methods/attributes of product. It's the convention in Ruby to use snake_case for method names and variables. If you named your columns productName and productLink, you'll have to rename them though to be able to use 'snake_case'. In Ruby, CamelCase is used for Class and ModuleNames.

    Hope that helps!

提交回复
热议问题