0

我正在关注这篇文章,以便在 ruby​​ on rails 中将用户添加为好友

http://asciicasts.com/episodes/163-self-referential-association

我可以通过 Rails 控制台将用户添加为朋友,但不能通过实际页面...这是我的控制器代码

class FriendshipsController < ApplicationController
  def new
  end

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

  def show
  end
end

型号: 用户:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
has_many :contacts
has_many :phones
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  
  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :user_id
  # attr_accessible :title, :body
end

朋友们:

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

看法:

<h1>Phones#index</h1>
<center>Users in the system<center><br/>
<p><% @phones.each do |variable|%>
    <% if @phn.email!= variable.email %>
    <br/><%= variable.email %> &nbsp; <%= link_to 'Add as Friend' , friendships_path(:friend_id => @user), :method => :post %>
    <%end%>
    <%end%>
<p>friends</p>
<% for user in current_user.friends %>
<p><%= user.email %></p>
<%end%>

我的视图工作正常.. 如果我通过控制台添加朋友并提交它,它会显示在视图中.. 我哪里出错了?

4

1 回答 1

0

我能够更正它..我的视图文件中有错误的代码..非常感谢 jvnill....如果不是你,我不会检查我的视图文件... :)

更改friendships_path(:friend_id => @user)friendships_path(:friend_id => variable) did the trick

于 2013-02-25T12:14:26.983 回答