【发布时间】:2015-07-08 11:44:18
【问题描述】:
我有两个模型,
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to: user
end
我正在使用formtastic gem,请考虑users_controller 的edit 操作。表单的所有必需的user 和关联的posts 属性将由formtastic 表单预填充
代码:
<%= semantic_form_for @user do |f| %>
<%= f.input :name %>
<%= f.inputs :posts do |p| %>
<%= p.input :title %>
<%= p.input :comment %>
<% end %>
<% end %>
例如,我有一个 @user 和两个 posts 关联。
在做@user.posts的时候,结果是这样的。
[
[0] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[1] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
}
]
因此表单将包含两个要编辑的帖子字段。
实际上,我想要在这两个帖子之前再添加一个空白表单。
这可以通过在第 0 位的 @object.posts 结果中插入一个新的空 post 对象来轻松实现。
所以,我想要的 @object.posts 结果应该看起来像,
[
[0] #<Post:0x0000000aa53a50> {
:id => nil,
:title => nil,
:comment => nil
},
[1] #<Post:0x0000000aa53a20> {
:id => 3,
:title => 'Hello World',
:comment => 'Long text comes here'
},
[2] #<Post:0x0000000aa53a41> {
:id => 5,
:title => 'Hello World 2',
:comment => 'Long text comes here too'
}
]
从@user.posts获取此结构的任何解决方案?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 formtastic