Mongoid Twitter式下面,不能指定关系数组的条件/条件

时间:2010-06-21 15:29:50

标签: ruby-on-rails database mongoid

我正在努力处理这些错误。基本上,我创建了以下用户和关系模式,使用Mongoid来处理我的数据库。这似乎是页面底部here的示例的近碳复制品。我试图调用以下任何一个:

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。

我不确定在线发布代码或从gist发布代码是否更好,所以这里有一些要点:

user.rb
user_follow_spec.rb
relationship.rb

我将不胜感激。

3 个答案:

答案 0 :(得分: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 :(得分: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

答案 2 :(得分: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 / fan_of”替换为“追随者/后续”。希望这会有所帮助。