我一直被困在这个里面。我在用户,友谊和配置文件模型之间有很多关系。似乎没有什么对我有用,我有点沮丧。请问谁能帮我?
错误发生在此代码块中
<%= friendship.friend.profile.name %>
错误消息是:
block in _app_views_users_show_html_erb__2756270183135360761_70272652488180
和
_app_views_users_show_html_erb__2756270183135360761_70272652488180
在我的用户/显示.html.erb
<h4> <%= current_user.profile.name%> Friends</h4>
<ul>
<% for friendship in @user.friendships %>
<li>
<%= friendship.friend.profile.name %>
(<%= link_to "remove", friendship, :method => :delete %>)
</li>
<% end %>
</ul>
在用户.rb 模型中
has_many :friendships
has_many :friends, through: :friendships
has_one :profile
在友谊.rb 模型中
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
belongs_to :profile
end
在配置文件.rb 模型中
class Profile < ActiveRecord::Base
belongs_to :user
has_many :friendships
has_many :friends, through: :friendships
end
在路线中.rb
Rails.application.routes.draw do
devise_for :users, :controllers => { registrations: 'registrations' }
resources :users do
resource :profile
end
resources :friendships
end
在users_controller.rb
def show
@user = current_user
@user = User.find(params[:id])
end
您说应用程序中只有两个用户,他们都是朋友,但根据您在 Zaid 答案的评论中发布的User.last.friendships
的控制台输出,有 3 个不同的用户 ID(6、2 和 5)。联接表中似乎有一个不再存在的用户的幽灵友谊。这会导致您收到错误。
因为当您尝试在friend
上调用profile
时会发生错误,所以我假设丢失的用户是 2 或 5。
您应该手动删除错误的友谊,并在用户模型中has_many :friendships
后添加一个dependent: :destroy
,以避免将来重复该问题。
您的current_user正在评估为零,因此它试图将配置文件放在 nil 上。所以你必须处理这个问题