Ruby on rails RubyonRails关系错误
我对RubyonRails中的关系有问题 我在两个表Ruby on rails RubyonRails关系错误,ruby-on-rails,relationship,null,has-one,Ruby On Rails,Relationship,Null,Has One,我对RubyonRails中的关系有问题 我在两个表Professionals和Users之间有1:1的关系。所以我用了属于并且有一个 professional.rb class Professional < ActiveRecord::Base attr_accessible :id, :nid has_one :user end class User < ActiveRecord::Base require 'digest/md5' attr_accessi
Professionals
和Users
之间有1:1的关系。所以我用了属于并且有一个
professional.rb
class Professional < ActiveRecord::Base
attr_accessible :id, :nid
has_one :user
end
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
class Professional
user.rb
class Professional < ActiveRecord::Base
attr_accessible :id, :nid
has_one :user
end
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
class用户
我的问题是当我想一行一行地显示时,我得到了这个错误
undefined method `id' for nil:NilClass
<td><%= item.professional.id %></td>
nil:NilClass的未定义方法'id'
这是我的index.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 !@users.blank? %>
<% 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>
用户仪表板
显示所有用户的信息
'获取'执行%>
零%>
身份证件
名字
姓氏
电子邮件
国民身份证
我希望你们能帮助我。这可能是因为没有为特定用户分配任何专业记录。要防止没有专业记录的用户出现错误,可以执行以下操作:
<td><%= item.professional.id if item.professional.present? %></td>
这可能是因为没有为该特定用户分配Professional
记录。首先向用户添加Professional
记录,然后再次测试。如果这就是问题所在,为了防止出现错误,您可以这样做:
这是因为我的用户表中有2条记录,其中1条没有专业id。问题解决了,谢谢大家!太好了,我会发布一个答案,如果你高兴的话,你可以接受。