2015-08-09 79 views
0

我正在開發一個項目,我將在一節的結尾處測試用戶。使用嵌套模型表格我希望users能夠選擇answers並將其存儲。我正在努力爲自己完善自己,並且可以使用來自更有經驗的開發人員的建議,以便如何最好地實現這一目標。Rails 4:使用嵌套模型表單保存用戶選擇

我認爲這是多對多的關係,我需要一個加入表格,但我不清楚如何表面允許users選擇他們的answers。我需要爲這個新的加入表創建一個控制器還是我誤解了這種情況下的ActiveRecord

我的模型是:如何最好地實現我的目標

class User < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
end 

class Test < ActiveRecord::Base 
    has_many :questions, :dependent => :destroy 
    accepts_nested_attributes_for :questions 
end 

class Question < ActiveRecord::Base 
    belongs_to :test 
    has_many :answers, :dependent => :destroy 
    accepts_nested_attributes_for :answers 
end 

class Answer < ActiveRecord::Base 
    belongs_to :question 
end 

任何有識之士/建議將非常感激。

+0

觀看關於'nested-forms'的視頻http://railscasts.com/episodes/196-nested-model-form-part-1 – Emu

回答

1

您可以嘗試不同的解決方案。一種方法是通過問題建立測試和答案之間的關聯。

user.rb

class User < ActiveRecord::Base 
    has_one :test 
end 

test.rb

class Test < ActiveRecord::Base 
    belongs_to :user 
    has_many :answers, dependent: :destroy 
    has_many :questions, through: :answers 

    accepts_nested_attributes_for :answers, allow_destroy: true 
end 

question.rb

class Question < ActiveRecord::Base 
    has_many :answers, dependent: :destroy 
end 

answer.rb

class Answer < ActiveRecord::Base 
    belongs_to :test 
    belongs_to :question 
end 

至於允許用戶選擇答案,您可能需要設置單獨的關聯,以便通過selected_answers獲得許多selected_answers和許多possible_answers的答案。也許從設置測試和答案開始,然後繼續選擇答案。

+0

感謝您的快速回放Margo。我會試一試,讓你知道它是如何發展的。從一個累人的讚賞:) – Ryan

相關問題