Reputation: 119
I have a problem with relationships in ruby on rails.
I have a 1:1 relationship between two tables Professionals
and Users
. So I used belongs_to
and has_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
My problem is when I want to show one by one row, I got this error
undefined method `id' for nil:NilClass
<td><%= item.professional.id %></td>
and this is my code for 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 [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>
I hope you can help me guys.
Upvotes: 0
Views: 67
Reputation: 2691
It's probably happening because no Professional record has been assigned to that particular user. To prevent the error for users that have no professional record you can do this:
<td><%= item.professional.id if item.professional.present? %></td>
Upvotes: 1