Cornelius Wilson
Cornelius Wilson

Reputation: 2914

List of users showing the same information

I am showing the subscription information for all users. The issue I have is that it is not displaying the correct information. It is showing the current_user subscription information for all the Users. When it should be displaying each users unique subscription information.

Admin views:

<% @users.each do |user| %>
<li>
<%= link_to user.username, user %>
|<%= @user.subscription.id %>|<%= @user.subscription.plan.name %>| <%= @user.subscription.created_at.strftime("%B %e, %Y") %>
</li>
<% end %>

Admin controller:

  def index
    @user = current_user
    @users = @user.present? ? User.where('id != ?',@user.id) : User.all

    render layout: 'new_application'    
  end

  def show
    @user = User.find_by(username: params[:id])
  end

Error: NoMethodError: undefined method `id' for nil:NilClass

Upvotes: 0

Views: 35

Answers (1)

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14401

It seems like the template should refer to user, not @user.

Update:

As @rlecaro2 mentioned, it's possible you've got some users with any subscriptions. In the case, calling .subscription on the user variables returns nil and you crash while asking for its id.

<% @users.each do |user| %>
  <li>
    <%= link_to user.username, user %>
    <% if user.subscription %>
      |<%= user.subscription.id %>|<%= user.subscription.plan.name %>| <%= user.subscription.created_at.strftime("%B %e, %Y") %>
    <% end %>
  </li>
<% end %>

Also since you're asking every user for its subscription and later on for the subscription's plan, you should explicitly load these to avoid unnecessary queries. For Rails 4, the Admin controller should look like this:

def index
  @users = User.includes(subscription: :plan)
  @users = @users.where.not(id: current_user.id) if current_user

  render layout: 'new_application'
end

Note that it's not necessary to carry the current_user via @user. You can refer to it in the template directly.

Upvotes: 4

Related Questions