【问题标题】:Submit into two tables with single form submit使用单个表单提交到两个表中
【发布时间】:2014-03-07 09:45:39
【问题描述】:

有什么方法可以提交到单个rails form_for/simple_form_for 中的两个表中,这两个表相互关联?

例子:-

<%= form_for @ob do |f| %>
<%= f.text_field :name %>
<%= f.text_field :another_col --> this is another table column(having association)

<%f.button :submit %>
<%end%>

【问题讨论】:

标签: ruby-on-rails ruby forms simple-form


【解决方案1】:

诀窍是将accepts_nested_attributes_for 添加到您的父模型中,并按照以下方式进行操作

型号

class Ob < ActiveRecord::Base
  has_many :foo
  accepts_nested_attributes_for :foo, allow_destroy: true
end

ERB

<%= form_for @ob do |f| %>
  <%= f.text_field :name %>
  <% f.foo do |fo| %>
     <%= fo.text_field :another_col %> <%=# this is another table column(having association)%>
  <% end %>

  <%f.button :submit %>
<%end%>

控制器

#your params would look like below
params = { ob: {
  name: 'joe', foos_attributes: [
    { another_col: 'Bar' }
  ]
}}
Ob.create(params[:ob])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    • 2018-03-09
    • 1970-01-01
    相关资源
    最近更新 更多