2010-06-21 24 views
1

我在我的智慧的結尾試圖處理這些錯誤。基本上,我創建了以下用戶和關係模式,使用Mongoid來處理我的數據庫。這看起來像是頁面底部here底部示例的近似副本。我試圖調用以下任何一種:Mongoid Twitter風格以下,不能指定關係數組的條件/條件

user1.relationships.find(:all, :conditions => {:rel_user => user_in_question, :rel_type => "following" }) 
user1.relationships.all(:conditions => {:rel_user => user_in_question, :rel_type => "following" }) 
user1.relationships.where(:rel_type => "following") 
user1.relationships.following #with a named scope 

這些似乎只是返回整個關係數組;他們不按標準搜索。 find()方法也會拋出一個錯誤,說它只能有1個參數。 im_following?方法總是返回true。

我不知道情況是否好轉後在線或要點代碼,所以這裏的要旨:

user.rb
user_follow_spec.rb
relationship.rb

我希望得到任何幫助。

回答

1

Rockmanioff,我有也遇到了同樣的問題。你也可以看看this。 Mongoid計劃在其發佈候選版本上支持該功能。目前,我們必須手動完成任務。

class User 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    references_many :fans, :stored_as => :array, :class_name => 'User', :inverse_of => :fan_of 
    references_many :fan_of, :stored_as => :array, :class_name => 'User', :inverse_of => :fans 

    def become_fan_of user 
    fan_of << user 
    self.save 

    user.fans << self 
    user.save 
    end 

    def is_a_fan? user 
    fan_of_ids.include? user.id 
    end 

    def unfan user 
    fan_of_ids.delete user.id 
    self.save 

    user.fan_ids.delete self.id 
    user.save 
    end 

    ... 
end 

在控制檯,你可以這樣做:

User.first.become_fan_of User.last 
User.first.is_a_fan? User.last 
User.first.unfan User.last 

你的情況,你可能想替換 「風扇/ fan_of」 爲 「追隨者/以下的分別」。希望這可以幫助。

1

我建議你通過使用自引用關聯來簡化你的關係。看看我這個問題的答案:

How-to: User has fans

我覺得這是非常接近的關係,你想:

class User 
    include Mongoid::Document 
    references_many :following, 
        :class_name => 'User', 
        :stored_as => :array, 
        :inverse_of => :followed_by 

    references_many :followed_by, 
        :class_name => 'User', 
        :stored_as => :array, 
        :inverse_of => :following 
end 

# let's say we have users: al, ed, sports_star, movie_star  
sports_star.followed_by << al 
movie_star.followed_by << al 
sports_star.followed_by << ed 
movie_star.followed_by << ed 

movie_star.followed_by # => al, ed 
al.following   # => sports_star, movie_star 
1

試試這個:

class User 

    # follows and followers 
    references_many :follows, :stored_as => :array , :inverse_of => :followers ,:class_name=>"User" 
    references_many :followers, :stored_as => :array , :inverse_of => :follows ,:class_name=>"User" 


    def followers 
    followers.map 
    end 

end