构建此Rails测验模型的更有效方法是什么?

时间:2017-11-03 12:50:33

标签: ruby-on-rails

他们说铁轨范例是不重复自己,或“干”。所以我正在研究这个测验应用程序,现在我已经慢慢了解MVC如何工作以及如何将它们组合在一起,我想编写更好的代码。那么让我们从我的架构中做到的这个例子:

create_table "posts", force: :cascade do |t|
    t.text "title"
    t.text "text"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "user_id"
    t.text "answer_choice"
    t.text "answer_choice_2"
    t.text "answer_choice_3"
    t.text "answer_choice_4"
    t.text "answer_choice_5"
    t.text "correct_answer_choice"
    t.string "slug"
    t.index ["slug"], name: "index_posts_on_slug", unique: true
  end

正如你所看到的,answer_choice,然后添加_2,_3,_4,_5和correct_answer_choice对我来说似乎非常难看和低效。如果我想添加一个只有两个答案选项的帖子怎么办?还是三个?也许更多?

什么是更好的解决方法,以便更具适应性和灵活性?

1 个答案:

答案 0 :(得分:2)

每个帖子的表格中只有given_answercorrect_answer列会更简单。对于given_answer列,您可以使用options_for_select在表单中显示选项:

options_for_select([ "Choice1", "Choice2", etc... ]) 

提交后,您可以查询if correct_answer == given_answer以查看这两个值是否匹配。

相关问题