Ruby on Rails:如何从表单收集子表的值?
引用问题#2013421,我有以下 RoR 模型:
class Game < ActiveRecord::Base
has_many :piles
end
class Pile < ActiveRecord::Base
belongs_to :game
end
为了论证,假设 Game
有一个属性 name
,并且 Pile
有一个属性属性类型
,均为字符串
。每场比赛正好有 10 堆。
我想要一个 HTML 表单来创建一个新游戏,类似于 ruby script\generatescaffold 生成的游戏;就像:
<h1>New game</h1>
<% form_for(@game) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', games_path %>
如何向表单添加字段,以便读取 10 堆中每一堆的 Pile.type
字段的值?
Referencing question #2013421, I have the following RoR models:
class Game < ActiveRecord::Base
has_many :piles
end
class Pile < ActiveRecord::Base
belongs_to :game
end
For the sake of argument, suppose Game
has an attribute name
, and Pile
has an attribute type
, both string
. There are precisely 10 piles per game.
I would like a single HTML form to create a new Game, similar to the one generated by ruby script\generate scaffold
; that is like:
<h1>New game</h1>
<% form_for(@game) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', games_path %>
How can I add fields to the form in order to read values for the Pile.type
field for each of the 10 piles?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以执行以下操作:
model:
在您的表单中:
考虑“type”method-keyword-column 是由 ActiveRecord 保留的,以实现多态关联,
请参阅 有关 Rails 中嵌套表单的良好指南
You can do something like this:
model:
in your form:
Consider that 'type' method-keyword-column is reserved by ActiveRecord to achieve polymorphic associations
see a good guide about nested forms in rails