开发者

Rails - Accessing instance variable properties from an Index Action in a view

开发者 https://www.devze.com 2023-04-11 05:49 出处:网络
Models class Account < ActiveRecord::Base belongs_to :user end class User < ActiveRecord::Base has_one :account

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号