管理 rails 中两个 类 的多重关联

Manage multiple association of two classes in rails

我想管理一对多类型的关联,用于用户和答案以及多对多类型的关联,用于相同两个模型的投票管理,即用户和答案。

那么,如何同时维护这两个关联呢?

这段代码是我想实现的。

class User < ActiveRecord::Base    

 has_many :answers #For the answers of particular user

 has_and_belongs_to_many :answers #For the answers upvoted by a particular user

 end 

class Answer < ActiveRecord::Base

 belongs_to :user #Author of the answer

 has_and_belongs_to_many :users #For those who upvoted the answer

end

您应该为其他协会指定一个不同的名称,但您还需要指定 class 名称。

has_many :answers
has_and_belongs_to_many :voted_answers, class_name: "Answer"