Rails - Accessing instance variable properties from an Index Action in a view
Models
class Account < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_one :account
devise :database_authenticatable, :registerable,
:recoverable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
end
Controller
class AccountsController < ApplicationController
before_filter :authenticate_user!
def index
@accounts = Account.all
end
View
p id="notice"><%= notice %></p>
<table>
<tr>
<th>Account Number</th>
<th>User 开发者_JAVA百科Id</th>
<th>Email Address</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @accounts.each do |account| %>
</tr>
<td><%= account.Number %></td>
<td><%= account.user_id %></td>
<td><%= account.user.email %></td>
<td><%= link_to 'Show', account %></td>
<td><%= link_to 'Edit', edit_account_path(account) %></td>
<td><%= link_to 'Destroy', account, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Account', new_account_path %>
I can access account.user.email from my other actions but I'm stumped as to why I can't access it here and instead get undefined method 'email for nil:NilClass? Update: I needed to be checking for a nil value. Fixed it by putting the following in my view:
<%= account.user.email if account.user %>
The User Object is null, perhaps there is a Key missing from the Account record? I would throw an exception providing the Account PKEY and do a quick look through the database to ensure there is in fact a User key constrained to it.
Hope that helps debug.
精彩评论