将 Formtastic 的语义_字段_for 与 has_many 关联结合使用
我正在尝试使用 formattastic 创建嵌套表单。我已在下面包含了我的代码,但遇到了一些问题,我也在下面列出了这些问题。有什么建议吗?谢谢。
# Home model
class Home < ActiveRecord::Base
has_many :home_members
accepts_nested_attributes_for :home_members, :reject_if => :all_blank, :update_only => true, :allow_destroy => true
end
# Form builder in members/new.html.erb
<%= semantic_form_for @home, :url => home_members_path(@home), :html => { :method => :post }, :remote => true do |f| %>
<%= f.inputs do %>
<%= f.semantic_fields_for :home_members do |h| %>
<%= h.input :name %>
<%= h.input :email %>
<%= h.input :birthday, :as => :string %>
<% end %>
<% end %>
# members_controller's new method; @home is set in a before filter
def new
2.times{ @home.home_members.build }
end
保存主页时会创建默认用户。如何让表单仅显示新创建的记录而不显示现有记录?
如果#1 不可能,我如何更新现有记录?我在accepts_nested_attributes_for 上设置了update_only,但仍然创建了一条新记录。
我在控制器操作中执行 2.times{ @home.home_members.build } 。当我打印 @home.home_members 的大小时,我得到了 3 (一个已经存在),正如预期的那样。为什么表单只显示 2 组输入,其中一组使用现有的 home_member 数据填充?
I am trying to create a nested form using formtastic. I've included my code below but am running into some problems that I've also listed below. Any suggestions? Thanks.
# Home model
class Home < ActiveRecord::Base
has_many :home_members
accepts_nested_attributes_for :home_members, :reject_if => :all_blank, :update_only => true, :allow_destroy => true
end
# Form builder in members/new.html.erb
<%= semantic_form_for @home, :url => home_members_path(@home), :html => { :method => :post }, :remote => true do |f| %>
<%= f.inputs do %>
<%= f.semantic_fields_for :home_members do |h| %>
<%= h.input :name %>
<%= h.input :email %>
<%= h.input :birthday, :as => :string %>
<% end %>
<% end %>
# members_controller's new method; @home is set in a before filter
def new
2.times{ @home.home_members.build }
end
A default user is created when a Home is saved. How do I have the form display only the newly created records and not the existing one?
If #1 isn't possible, how do I make the existing record update? I have update_only set on the accepts_nested_attributes_for, but a new record is still created.
I am doing 2.times{ @home.home_members.build } in the controller action. When I print the size of @home.home_members I get 3 (one already exists) as expected. Why is the form only displaying 2 sets of inputs, one being populated with the existing home_member data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很好回答问题1)仅显示新创建的对象
well to answer question 1) show only the newly created objects
我过去曾成功地使用过 cocoon。 https://github.com/nathanvda/formtastic-cocoon
I've used cocoon with success in the past. https://github.com/nathanvda/formtastic-cocoon