0

我已经关注了 RyanB 的 railcast 163 on self-referential association to the letter,但我不断收到以下错误:

    NoMethodError in Users#show

    Showing /Users/markwalker/welcomepie/app/views/shared/_suggested_connections.html.erb where line #6 raised:

    undefined method `name' for nil:NilClass
    Extracted source (around line #6):

    3:          <ul>
    4:        <% for friendship in @user.friendships %>
    5:        <li>
    6:          <%= h friendship.friend.name %>
    7:          (<%= link_to "remove", friendship, :method => :delete %>)
    8:        </li>
    9:        <% end %> 

这是我的观点(它是在用户/显示页面中呈现的部分):

<div class="span5">
    <div class="MemberDisplay">
        <ul>
      <% for friendship in @user.friendships %>
      <li>
        <%= h friendship.friend.name %>
        (<%= link_to "remove", friendship, :method => :delete %>)
      </li>
      <% end %> 
    </ul>
    </div>
</div>

我的友谊模型:

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => 'User'
  attr_accessible :friend_id, :user_id

end

我的友谊控制器:

 class FriendshipsController < ApplicationController
  def create
    @friendship = current_user.friendships.build(:friend_id => params[:friend_id])
    if @friendship.save
      flash[:notice] = "Added friend."
      redirect_to root_url
    else
      flash[:error] = "Unable to add friend."
      redirect_to root_url
    end
  end

  def destroy
    @friendship = current_user.friendships.find(params[:id])
    @friendship.destroy
    flash[:notice] = "Removed friendship."
    redirect_to current_user
  end
end

我的用户模型:

class User < ActiveRecord::Base

has_many :friendships
has_many :friends, :through => :friendships

rolify
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model
attr_accessible :role_ids, :as => :admin
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
attr_accessible :occupation_list, :gender_list, :moving_from_list, :moving_to_list, :family_type_list, :age_bracket_list, :interest_list, :about_me, :username, :avatar
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
acts_as_taggable
acts_as_taggable_on :occupation, :gender, :moving_from, :moving_to, :family_type, :age_bracket, :interests
scope :by_join_date, order("created_at DESC")

私人的

def self.tag_tokens(query)
  tags = User.categories.where("name like ?", "%#{query}%")
  if tags.empty?
    [{id: "#{query}", name: "#{query}"}]
  else
    tags
  end
 end

end

我的用户控制器:

class UsersController < ApplicationController
before_filter :authenticate_user!

def index

  authorize! :index, @user, :message => 'Not authorized as an administrator.'
  @users = User.all

end

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

def new
  @user = User.new
end

def create
  @user = User.new(params[:user])
  if @user.save
    sign_in @user
    redirect_to users_path, :notice => "Welcome to WelcomePie!"
  else
    redirect_to new_users_path, :alert => "Please try signing up again"
  end
end

def edit
end 

def update
  authorize! :update, @user, :message => 'Not authorized as an administrator.'
  @user = User.find(params[:id])
  if @user.update_attributes(params[:user], :as => :admin)
    redirect_to user, :notice => "User updated."
  else
    redirect_to user, :alert => "Unable to update user."
  end
end

def destroy
  authorize! :destroy, @user, :message => 'Not authorized as an administrator.'
  user = User.find(params[:id])
  unless user == current_user
    user.destroy
    redirect_to users_path, :notice => "User deleted."
  else
    redirect_to users_path, :notice => "Can't delete yourself."
  end
end

def find_tags
  @tags = Video.tag_tokens(params[:q])
  respond_to do |format|
    format.html
    format.json { render json: @tags }
  end
end

结尾

还有我的路线:

      Welcomepie::Application.routes.draw do

  resources :friendships

  authenticated :user do
    root :to => 'home#index'
  end
  root :to => "home#index"
  devise_for :users, :controllers => { :registrations => :registrations }
  resources :users
end

有没有人知道为什么它不能识别friendship.friend.name?我认为这与设计有关,但我无法解决。

谢谢你的帮助!!

4

2 回答 2

0

您应该在 Friendship 模型中设置 :foreign_key

class Friendship < ActiveRecord::Base
  belongs_to :user, :foreign_key => :user_id
  belongs_to :friend, :class_name => 'User', :foreign_key => :friend_id
  attr_accessible :friend_id, :user_id
end
于 2012-11-21T13:54:33.197 回答
0

问题实际上是在索引视图中,即使错误发生在显示视图中。

问题是当我添加一个朋友时,他们的 ID 没有被设置,它被设置为零。这可能与教程是较旧的 Rails 语法有关。无论如何,为了让我工作,我需要向用户添加 .id 以正确设置 ID,如下所示:

<% if user_signed_in? %>
        <h3>Welcome back <%= current_user.name %>!</h3>
        <% else %>
        <h3>Please sign up <%= link_to 'here', new_user_registration_path %></h3>
        <% end %> 
            <% @users.each do |user| %>
                <p>User: <%=link_to user.name, @user %>
                <%= link_to "Add as friend", friendships_path(:friend_id => user.id), :method => :post %> </p>
            <% end %>
于 2012-11-21T17:49:15.313 回答