1

我正在尝试在以下关系中提取给定用户的所有帖子。不确定我是否正确,所以我会更好地解释。用户在某些组中拥有所有权和成员资格。用户可以是组的成员或所有者,但不能两者兼而有之。每个 Post 都有一个用户和组的 id。我认为问题是由于下面提到的关系。我怎样才能绕过它?还有一件事。我还必须找到用户组中其他用户发布的所有帖子。换句话说,我必须通过组。

       /-- Owner ---\
User --              -- Group -- Post
  |    \-- Member --/             |
  |_______________________________|

class User < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
  has_many :ownerships, :foreign_key => "user_id", :dependent => :destroy
  has_many :memberships, :foreign_key => "user_id", :dependent => :destroy

  # Problem with these two? I think so.
  has_many :groups, :through => :memberships, :source => :user
  has_many :groups, :through => :ownerships, :source => :user

class Ownership < ActiveRecord::Base
  belongs_to :users, :class_name => "User"
  belongs_to :groups, :class_name => "Group"
  has_many :posts, :through => :groups, :source => :posts

class Membership < ActiveRecord::Base
  belongs_to :users, :class_name => "User"
  belongs_to :groups, :class_name => "Group"
  has_many :posts, :through => :groups, :source => :posts

class Group < ActiveRecord::Base
  has_many :posts, :dependent => :destroy

class Post < ActiveRecord::Base
  belongs_to :user
  belongs_to :groups

错误来自以下行:

_groups = user.groups

错误如下:

找不到源关联:模型所有权中的用户。尝试 'has_many :groups, :through => :ownerships, :source => '。它是 :users、:groups 还是 :postings 之一?

4

1 回答 1

1

首先:您收到了您所看到的错误,因为您已将MembershipandOwnership表中的关联定义为:

belongs_to :users

当它们应该只属于一个用户时,即单数user

belongs_to :user

但即便如此,您也会遇到问题!

我认为拥有一个Membership模型和一个Ownership模型是接下来会绊倒你的东西。我不明白拥有一个Ownership模型的目的是什么,除了表示一个组的所有权,这可以通过例如memberships表记录上的一个字段来完成owner。这是过度工程。

您获得的 Rails 代码的问题在于,您通过一个关联定义了许多帖子,然后您告诉它您通过另一个关联有很多帖子。实际上,您正在这样做:

 def posts
   # find posts for the groups that I own
 end

 def posts
   # find posts for the groups I belong to
 end

这里有两个同名的方法并没有错。这正是您通过定义两个has_many具有相同名称的关联所做的事情。

所以希望现在你能明白为什么拥有一个Ownership和一个Membership模型是通往疯狂的道路。

I would really recommend that you just have a Membership model that has a boolean attribute declaring an owner for a group. This would also mean that, if you wanted to, you could have new owners for a group in a very easy fashion: just flip the boolean. No need to create another record in another table.

One Membership model to rule them all.

于 2011-09-12T23:20:17.820 回答