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 に答える