3

我有很多直通关系来定义用户回答的问题。

如何为用户创建的问题建立关系?

通常你只会在用户和问题之间创建一个 has_many 和 belongs_to 关系,但是因为我也在做一个 has_many ,所以这是行不通的。

这是我到目前为止所拥有的:

楷模:

Users
Questions
Answered_questions

用户模型

has_many :answered_questions
has_many :questions, :through => :answered_questions

问题模型:

has_many :answered_questions
has_many :users, :through => :answered_questions

Answered_questions 模型

belongs_to :question
belongs_to :user

编辑

我找到了这个答案:https ://stackoverflow.com/a/12637532/756623 ,这让我尝试了这个:

用户模型添加:

has_many :questions_created, :class_name => "Question", :inverse_of => :created_by

问题模型添加:

belongs_to :created_by, :class_name => "User", :foreign_key => "created_by_id", :inverse_of => :questions_created 

我还将该列添加created_by_id到问题表中

现在......user_id没有被添加到created_by_id列中。

我有什么问题?

4

1 回答 1

3

我认为这样的事情可能会解决您的问题:

# User
has_many :answered_questions
has_many :questions, :through => :answered_questions
has_many :created_questions, class_name: Question, foreign_key: :author_id

# Question
has_many :answered_questions
has_many :users, :through => :answered_questions
belongs_to :author, class_name: User

# Answered questions
belongs_to :question
belongs_to :user
于 2013-02-24T20:56:30.307 回答