【问题标题】:Rails 4: Saving User selections with a Nested Model FormRails 4:使用嵌套模型表单保存用户选择
【发布时间】:2015-08-09 00:21:39
【问题描述】:

我正在做一个项目,我需要在一个部分的末尾测试用户。使用嵌套模型表单,我希望 users 能够选择 answers 并存储它们。我正在尝试为自己构建它以进行改进,并且可以参考更有经验的开发人员关于如何最好地解决此问题的建议。

我假设这是多对多直通关系,我需要一个连接表,但我不清楚如何显示它以允许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

任何关于如何最好地实现我的目标的见解/建议将不胜感激。

【问题讨论】:

标签: ruby-on-rails devise rails-activerecord nested-forms


【解决方案1】:

您可以尝试不同的解决方案。一种方法是通过问题在测试和答案之间建立关联。

用户.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 

问题.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。也许从设置测试和答案开始,然后继续选择答案。

【讨论】:

  • 感谢您快速重播 Margo。我会试一试,让你知道它是怎么回事。非常感谢一个疲惫的人:)
猜你喜欢
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多