ruby-on-rails
  • ruby-on-rails-3
  • activerecord
  • activemodel
  • 2011-12-22 57 views 0 likes 
    0

    問題:@ user.friends不起作用。它返回2條記錄,它應該是4 ..在rails中創建友誼模型關聯

    我有以下型號:

    class User < ActiveRecord::Base 
        has_many :friendships 
        has_many :friends, 
        :through => :friendships, 
        :conditions => "status = 'accepted'", 
        :order => :fname 
        has_many :requested_friends, 
        :through => :friendships, 
        :source => :friend, 
        :conditions => "status = 'requested'" 
        has_many :pending_friends, 
        :through => :friendships, 
        :source => :friend, 
        :conditions => "status = 'pending'" 
    
    class Friendship < ActiveRecord::Base 
        belongs_to :user 
        belongs_to :friend, :class_name => "User", :foreign_key => "friend_id" 
    

    出於某種原因。 <%[email protected]%>未返回所有用戶的朋友。

    實施例的數據:上述

    > @user.friendships.all.length 
    => 4 
    > @user.friendships 
    => [#<Friendship id: 20, user_id: 11, friend_id: 20, status: "accepted", created_at: "2011-12-22 12:59:22", updated_at: "2011-12-22 17:02:54">, #<Friendship id: 8, user_id: 11, friend_id: 12, status: "accepted", created_at: "2011-12-22 06:29:02", updated_at: "2011-12-22 07:41:24">, #<Friendship id: 3, user_id: 11, friend_id: 1, status: "approved", created_at: "2011-12-22 05:48:29", updated_at: "2011-12-22 06:22:09">, #<Friendship id: 1, user_id: 11, friend_id: 641, status: "approved", created_at: "2011-12-22 04:47:19", updated_at: "2011-12-22 04:47:19">] 
    > @user.friends.length 
    => 2 
    

    @ user.friends.length應該已經4作爲數據顯示的所有狀態爲 「接受」。任何想法,我在上面列出的模型協會搞砸了嗎?

    謝謝!

    回答

    3

    狀態是「批准」爲兩個友誼和「接受」兩個。這就是爲什麼它只返回兩個接受友誼根據您的條件。

    +0

    非常感謝! – AnApprentice 2011-12-22 18:39:24

    相關問題