2014-10-26 56 views
0

我在轨道上的红宝石关系有问题。轨道上的红宝石关系错误

我在两个表格ProfessionalsUsers之间有1:1的关系。所以我用belongs_tohas_one

professional.rb

class Professional < ActiveRecord::Base 
    attr_accessible :id, :nid 
    has_one :user 
end 

user.rb

class User < ActiveRecord::Base 
    require 'digest/md5' 

    attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :professional_id 
    before_save :encrypt_password 
    belongs_to :professional 
end 

我的问题是,当我想以一个行显示一个,我得到这个错误

undefined method `id' for nil:NilClass 

<td><%= item.professional.id %></td> 

这是我的代码ex.html.erb

<h2>User Dashboard</h2> 
<%= link_to "Log Out", logout_path %><br /> 
<%= link_to "Create a User", '/register' %> 
<%= link_to_function "Back", "history.back()" %> 
<hr> 
Display all users' information<br /> 
<%= form_tag users_path, :method => 'get' do %> 
    <p> 
    <%= text_field_tag :search, params[:search] %> 
    <%= submit_tag "Search", :first_name => nil %> 
    </p> 
<% end %> 

<table width="0%" border="0"> 
    <tr> 
    <th scope="col">ID</th> 
    <th scope="col">Firstname</th> 
    <th scope="col">Lastname</th> 
    <th scope="col">Email</th> 
    <th scope="col">National ID</th> 
    </tr> 
    <% if [email protected]? %> 
    <% for item in @users %> 
    <tr> 
    <td><%= link_to item.id, user_path(item) %></td> 
    <td><%= item.first_name %></td> 
    <td><%= item.last_name %></td> 
    <td><%= item.email %></td> 
    <td><%= item.professional.id %></td> 
    </tr> 
    <% end %> 
<% else %> 
<% end %> 
</table> 

我希望你能帮助我。

+0

可能发生这种情况,因为没有专业记录已分配给该特定用户。首先向用户添加“Professional”记录并再次测试。如果这是问题,为了防止错误,你可以这样做:'​​<%= item.professional.id if item.professional.present? %>' – Alireza 2014-10-26 20:15:50

+0

这是因为我的用户表中有2条记录中有1条没有profesisonal_id。问题解决了,谢谢你们! – rfcabal 2014-10-26 20:21:11

+0

太棒了,我会发布一个答案,如果你感到高兴,你可以接受它。 – Alireza 2014-10-26 20:47:27

回答

1

这可能是因为没有专业记录已被分配给该特定用户。为防止没有专业记录的用户出现错误,您可以这样做:

<td><%= item.professional.id if item.professional.present? %></td>