提交到两个表格,提交单一表格

时间:2014-03-07 09:45:39

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

有没有办法我们可以在单个rails_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%>

1 个答案:

答案 0 :(得分:0)

诀窍是将accepts_nested_attributes_for添加到您的父模型,并执行以下操作

MODEL

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%>

CONTROLLER

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