0
模型/ user.rb在一個沒有錯誤的方法一對多關係
class User < ActiveRecord::Base
has_many :clubs, :dependent => :destroy
has_many :announcements, :dependent => :destroy
end
模型/ announcement.rb
class Announcement < ActiveRecord::Base
belongs_to :user
belongs_to :club
end
模型/ club.rb
class Club < ActiveRecord::Base
belongs_to :user
has_many :announcements, :dependent => :destroy
end
控制器/通知/announcements_controller.rb
def index
@announcements = Announcement.find(:all, :include => [:user, :club])
end
問題:
當我輸入驗證碼,
的意見/公告/ index.html.erb
<% @announcements.each do |announcement| %>
<%= announcement.user.username %>
<% end %>
我得到這個錯誤:
NoMethodError in Announcements#index
undefined method `username' for nil:NilClass
時我將代碼更改爲此,它的工作原理。
<% @announcements.each do |announcement| %>
<%= announcement.club.user.username %>
<% end %>
爲什麼第一個代碼不起作用?這些代碼有什麼區別。謝謝。
聽起來像您的公告之一沒有用戶關聯。使用`rails console`並檢查你的Announcements對象,看看是否是這種情況。 – 2010-12-21 19:58:55