2014-10-06 59 views
1

最近我碰到,我需要一个模型添加到另一个模型不止一次几个方案。Rails的一个模型添加到另一种模式的两倍

示例:

说一个用户有一个帖子。但该帖子也应该能够与其他用户共享,以便这些用户可以查看/编辑该帖子。所以帖子应该属于一个用户,但也应该有一个用户的数组,也可以编辑它。

或者说一个调查应该有很多问题,但也应该有一些问题,是独立的筛选问题。所以调查应该有很多问题,但也可能有很多筛选问题。

我怎么会去有关添加指向第二个数据库字段相同的模型作为不同领域?现在邮政将有user_id:integer,每个问题将有一个survey_id:integer

对于有问题的调查,我想我大概一个“筛选”布尔属性只是添加了问题,然后就被筛选属性添加的所有问题的survey.questions阵列和过滤器。但我不确定这是最佳路线。

我不知道如何处理与用户模型共享的帖子,虽然用户has_many帖子,但每个帖子可以与多个其他用户共享。

回答

2

Looks like you need a has_many, :through relation

您卸载user_id不同的表(通过自定义模型,比方说,PostRelation定义),其中列的样子:
user_id | post_id | kind | created_at | updated_at

您定义的kind列的一种关系(如“视图','编辑','所有者')和post_iduser_id是不言自明的。

在这种情况下,关系将是:

  • has_many :users, through: :post_relation
  • has_many :post_relations
  • 用户has_many :posts, through: :post_relation
  • 用户has_many :post_relations
  • PostRelation belongs_to :user
  • PostRelation belongs_to :post

然后用户/ posts模型中,你可以定义过滤基础上,PostRelation地位的帖子自定义的方法:

class Post def editors self.post_relations.includes(:users).where(kind: 'edit') end end

+0

正是我需要的。这很棒 – 2014-10-06 02:11:35

相关问题