我有一個有很多直通關係來定義用戶已回答的問題。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