2011-12-20 40 views
1

我有一个标准的关系:我可以在多对多的关系中添加到现有的连接表模型吗?

class User <ActiveRecord:: Base 
    has_and_belongs_to_many: feeds,: uniq => true 
end 

class Feed <ActiveRecord:: Base 
    has_and_belongs_to_many: users,: uniq => true 
end 

而按照Rails的命名惯例,连接表被称为 “users_feeds”。

我需要扩展连接表的功能,并添加模型UserFeed(或UsersFeeds?)。

  1. 添加模型是否是轨道约定的障碍?
  2. 我是否需要更改连接表的名称,并使用以下选项定义关系:through?

回答

6

为您的连接模型添加一个类没有问题。你不需要改变表名。由此产生的代码将如下所示:

class User <ActiveRecord:: Base 
    has_many :user_feeds 
    has_many :feeds, :through=>:user_feeds 
end 

class UserFeed <ActiveRecord:: Base 
    belongs_to :user 
    belongs_to :feed 
end 

class Feed <ActiveRecord:: Base 
    has_many :user_feeds 
    has_and_belongs_to_many: users, :through=>:user_feeds 
end