在轨道上添加红宝石的朋友

时间:2013-02-25 11:37:22

标签: ruby-on-rails

我正在关注这篇文章,将用户添加为ruby on rails的朋友

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

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

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%>

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

1 个答案:

答案 0 :(得分:0)

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

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