【发布时间】:2016-03-03 23:35:40
【问题描述】:
我真的不知道为什么会出现这个错误....今天早些时候这工作正常,然后我做了一些修改,显然我迷失了方向,现在当我启动我的应用程序时,我总是当我尝试以用户身份登录时出现此错误。
NoMethodError in Users#show
undefined method `friendships' for #<Profile:0x007ff052f60b68>
我的应用中有 3 个用户,他们都有个人资料。
在 current_user 个人资料页面上,用户可以看到他的朋友并点击他们的名字来查看他们的个人资料。
谁能帮我解决这个问题? TIA大地
在views/users/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
已编辑
在同一个视图中,我链接到同一条路线并且它有效,这是为什么呢?我的意思是这基本上是相同的链接? (见下文)
<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>
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 many-to-many