Accessing one controller variable in another controller in Rails

Viewed 7083

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 of a problem I am hitting. I have a User and a Product model. In the Product DB I store different products and one of the fields is a userid field that matches the userid stored in the User table. After the user logs in - I display the user's name, email etc (this is stored in @current_user) and then have a link to show different products owned by the user. I do this via the following code in users/show.html.erb like this: ...

Name: <%= @current_user.name %>

... <%= link_to "Products", products_path, id: "products" %>

So far so good. When I click the "Products" link it takes me to products/index.html.erb and the following code gets executed (I want to filter this display to show only products owned by @current_user.userid. How do I do this? The following code gives me a runtime error as @current_user evaluates to nil I believe. If I remove the "if" clause then all products ar displayed which is not what I want. Would be grateful for any tips.

<tbody>
<% @products.each do |product| %>
  <tr>
    <td><%= product.userid if product.userid == @current_user.userid %></td>
    <td><%= product.productName if product.userid == @current_user.userid %></td>
    <td><%= product.productLink if product.userid == @current_user.userid %></td>

Thanks,

3 Answers
Related