group model 代码
class Group < ActiveRecord::Base
has_many :posts
belongs_to :owner, :class_name => "User", :foreign_key => :user_id
has_many :group_users
has_many :participated_groups, :through => :group_users, :source => :group
validates :title, :presence => true
def editable_by?(user)
user && user == owner
end
end
user model 代码
class User < ActiveRecord::Base
has_many :groups
has_many :posts
extend OmniauthCallbacks
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
def join!(group)
participated_groups << group
end
def quit!(group)
participated_groups.delete(group)
end
after_create :join_owner_to_group
def is_member_of?(group)
participated_groups.include?(group)
end
def join_owner_to_group
members << owner
end
end
group view 代码
<div class="span12">
<div class="group">
<%= link_to("New group", new_group_path , :class => "btn btn-mini btn-primary pull-right")%>
</div>
<table class="table">
<thead> <tr>
<td> # </td>
<td> Title </td>
<td> Descroption </td>
<td> Owner </td>
</tr>
</thead>
<tbody>
<% @groups.each do |group| %>
<tr>
<td> # </td>
<td> <%= link_to(group.title, group_path(group)) %> </td>
<td> <%= group.description %> </td>
<td> <%= group.owner.name %> </td>
<td>
<% if current_user && group.editable_by?(current_user) %>
<%= link_to("Edit", edit_group_path(group), :class => "btn btn-mini")%>
<%= link_to("Delete", group_path(group), :class => "btn btn-mini",:method => :delete, :confirm => "Are you sure?" ) %>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
然后运行报错
NoMethodError at /
undefined method `name' for nil:NilClass 错误代码指向这一行
<%= group.owner.name %> 请指教。