我是新来的,对不起,如果这是一个非常基本的问题。
所以,在我的应用程序中,我有测验和每个测验,除了问题和答案,应该有5个链接。
class Quiz < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :questions
has_many :links
end
class Link < ActiveRecord::Base
belongs_to :quizzes
end
Schema看起来像这样:
create_table "links", force: true do |t|
t.string "name"
t.string "www"
t.integer "quiz_id"
end
create_table "questions", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "quiz_id"
end
create_table "quizzes", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
end
现在,在视图中,我想添加/编辑我的测验时添加链接。 表单视图如下所示:
<%= form_for(@quiz) do |f| %>
<% if @quiz.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@quiz.errors.count, "error") %> prohibited this quiz from being saved:</h2>
<ul>
<% @quiz.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content %>
<%= **THIS IS PLACE FOR TEXT FIELD FOR LINK_NAME AND LINK_WWW** %>
</div>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
如何创建表单以添加链接?
答案 0 :(得分:1)
您可以使用fields_for
:
<%= f.label :content %><br>
<%= f.text_field :content %>
<%= f.fields_for @quiz.links.new do |ff| %>
<%= ff.label :name %>
<%= ff.text_field :name %>
<% end %>
允许测验更新相关的链接记录:
class Quiz < ActiveRecord::Base
accepts_nested_attributes_for :links