我有一个有很多直通关系来定义用户已回答的问题。Rails:has_many通过两个模型之间,has_many /属于同一模型
如何为用户创建的问题建立关系?
通常情况下,您只需创建一个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
列的问题表
。
我有什么问题?
如何你想添加的'created_by_id'? – 2013-02-24 20:33:12
我认为这可能是我的问题....我不知道如何添加created_by_id ... – 2013-02-24 21:31:05
正在创建问题时将会添加'created_by_id'。因此,在您的控制器中,您可以尝试像'@question = current_user.questions_created.new(params [:question])',然后通过'@ question.save'保存。或者你使用的任何逻辑,你只需要通过'user_instance.created_question_association'调用这个问题。 – 2013-02-25 07:27:44