1

我在试图处理这些错误时束手无策。基本上,我创建了以下用户和关系模式,使用 Mongoid 来处理我的数据库。这似乎是此处页面底部示例的近似副本。我正在尝试调用以下任何内容:

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?方法总是返回真。

我不确定是在线发布代码还是从要点发布代码更好,所以这里是要点:

user.rb
user_follow_spec.rb
关系.rb

我将不胜感激任何帮助。

4

3 回答 3

1

我建议您通过使用自引用关联来简化您的关系。看看我对这个问题的回答:

操作方法:用户有粉丝

我认为这非常接近您想要的关联:

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
于 2010-11-22T09:52:22.050 回答
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
于 2010-11-22T10:26:23.547 回答
1

Rockmanioff,我也遇到了同样的问题。你可能也想看看这个。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”替换“followers / following”。希望这可以帮助。

于 2010-11-29T10:51:33.973 回答