我不能真正弄清楚为什么我得到这个错误....今天早些时候这工作得很好,然后我做了我明显失去了一些修改,现在当我启动我的应用程序时,当我尝试以用户身份登录时,总是遇到此错误。NoMethodError在用户#显示/未定义的方法`友谊'为#<个人资料:0x007ff052f60b68> Rails
NoMethodError in Users#show
undefined method `friendships' for #<Profile:0x007ff052f60b68>
我有3个用户在我的应用程序,他们都有配置文件。
在current_user配置文件页面上,用户可以看到他的朋友并单击他们的姓名以查看他们的个人资料。
任何人都可以帮助我吗? TIA大地
在视图/用户/ show.html.erb
<h4> <%= current_user.profile.name%> Friends</h4>
<ul>
<% @user.friendships.each do |friendship| %>
<li>
<%= link_to user_profile_path(user), :method => :get do %>
<%= friendship.friend.profile.name %>
<%#= link_to compare_friends_path(@user), :method => :get do %>
<%#= friendship.friend.profile.name %>
(<%= link_to "remove friend", friendship, :method => :delete %>)
</li>
<% end %>
<% end %>
</ul>
在users_controller.rb
def show
@user = User.find(params[:id]).profile
end
在user.rb模型
has_many :friendships
has_many :friends, through: :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, through: :inverse_friendships, :source => :user
has_one :profile
在profiles_controller。 rb
def show
@user = User.find(params[:user_id])
#@profile = @user.profile
end
在profile.rb模型
class Profile < ActiveRecord::Base
belongs_to :user
end
在friendship.rb模型
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
end
在routes.rb中
Rails.application.routes.draw do
devise_for :users, :controllers => { registrations: 'registrations' }
resources :users do
resource :profile
end
resources :friendships
end
EDITED
在同一视图中我链接到相同的路线,它的工作原理是什么?我的意思是这个链接基本相同? (见下文)
<h3>followers <%= current_user.profile.name%> </h3>
<ul>
<% @user.inverse_friends.each do |user| %>
<%= link_to user_profile_path(user), :method => :get do %>
<li><%= user.profile.name %></li>
<% end%>
<% end %>
</ul>
hi @Carpetsmoker,你是对的......当我删除.profile时,错误信息变为“未定义的局部变量或方法用户”为#<#:0x007ff054110c28>“”<% = link_to user_profile_path(user),:method =>:get do%>“ –
DaudiHell
我应该添加has_many:友谊到个人资料模型吗? – DaudiHell
@DaðiHall我想你想''用户'那里,为类变量,而不是'用户'为本地变量,它不存在。这就是错误所说的:“未定义的局部变量或方法”。 – Carpetsmoker