2016-03-03 23 views
1

我不能真正弄清楚为什么我得到这个错误....今天早些时候这工作得很好,然后我做了我明显失去了一些修改,现在当我启动我的应用程序时,当我尝试以用户身份登录时,总是遇到此错误。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> 

回答

0
def show 
    @user = User.find(params[:id]).profile 
end 

这似乎是错误的,因为你要指定User.profile@user

这会解释错误undefined method 'friendships' for #<Profile:0x007ff052f60b68>,因为您的User型号有has_many :friendships,但Profile没有。

注意:使用web_consolebetter_errors可以真正帮助追踪这样的问题,并且非常值得花一些时间设置。你的浏览器中有一个Ruby控制台出现异常,只要输入@user就会告诉你这是一个Profile实例,而不是User实例。

我做了一些修改,我清楚地失去了联系过

另一个教训:改变尽可能少,TEST,改变尽可能少,TEST,并不断重复这一点。这样,如果发生了什么事情,你就可以确切知道哪些更改会导致错误。尽可能缩短这个反馈回路。这也是一些工具,如better_errors确实有帮助。

有关更深入的说明,请参阅Feedback Loops in Software Development

+0

hi @Carpetsmoker,你是对的......当我删除.profile时,错误信息变为“未定义的局部变量或方法用户”为#<#:0x007ff054110c28>“”<% = link_to user_profile_path(user),:method =>:get do%>“ – DaudiHell

+0

我应该添加has_many:友谊到个人资料模型吗? – DaudiHell

+0

@DaðiHall我想你想''用户'那里,为类变量,而不是'用户'为本地变量,它不存在。这就是错误所说的:“未定义的局部变量或方法”。 – Carpetsmoker

相关问题