我有两个表,landslides和sources (可能没有关联)。我想要一个表格,让用户填写信息,然后提交给两个表格。下面是没有sources字段的当前表单:
= form_for :landslide, :url => {:controller => 'landslides', :action => 'create'} do |f|
.form-inputs
%form#landslideForm
.form-group.row
%label.col-sm-2.col-form-label{for: "textinput"}Date
.col-sm-10
= f.date_select :start_date, :class => "form-control"
#Some fields
.form-actions
= f.button :submit, class: "btn btn-lg btn-primary col-sm-offset-5", id: "submitButton"和参数:
def landslide_params
params.require(:landslide).permit(:start_date, :continent, :country, :location, :landslide_type, :lat, :lng, :mapped, :trigger, :spatial_area, :fatalities, :injuries, :notes)
end
def source_params
params.require(:source).permit(:url, :text, :landslide_id)
end此外,sources中还有一个列调用landslide_id,它从表landslides中获取滑坡ID。因此,当用户提交新的滑坡时,我如何获得即将到来的滑坡ID (这是自动增量,用户不需要填写)?
谢谢!
发布于 2017-04-26 22:00:14
HTML不允许嵌套的<form>元素,并且不能传递尚未通过表单持久化的记录id (因为它没有id)。
若要在同一个请求中创建嵌套资源,请使用accepts_nested_attributes_for
class Landslide
# or has_many
has_one :source
accepts_nested_attributes_for :source
end
class Source
belongs_to :landslide
end这意味着您可以执行Landslide.create(source_attributes: { foo: 'bar' }),它将同时创建Landslide和Source记录,并将通过sources.landslide_id自动链接它们。
要创建表单输入,请使用fields_for
# use convention over configuration
= form_for @landslide do |f|
.form-inputs
.form-group.row
# use the form builder to create labels instead
= f.label :start_date, class: 'col-sm-2 col-form-label'
.col-sm-10
= f.date_select :start_date, class: "form-control"
%fieldset
%legend Source
= f.fields_for :sources do |s|
.form-group.row
= s.label :url, class: 'col-sm-2 col-form-label'
.col-sm-10
= s.text_field :url, class: "form-control"
# ...class LandslidesController
# ...
def new
@landslide = Landslide.new
# this is needed to seed the form with inputs for source
@landslide.source.new
end
def create
@landslide = Landslide.new(landslide_params)
if @landslide.save
redirect_to @landslide
else
@landslide.source.new unless @landslide.source.any?
render :new
end
end
private
def landslide_params
params.require(:landslide).permit(
:start_date, :continent, :country,
:location, :landslide_type,
:lat, :lng, :mapped, :trigger, :spatial_area,
:fatalities, :injuries, :notes,
source_attributes: [ :url, :text ]
)
end
end发布于 2017-04-26 21:30:28
您需要使用accept_nested_attributes_for并相应地嵌套表单:
(对于应该嵌套哪种形式,我有保留,我以通过滑坡形式提交的源为例。)
在landslide.rb中
accept_nested_attributes_for :sources在你看来(我不认识哈梅尔,但无论如何)
<%= form_for :landslide do |f|%>
<%= f.select :start_date %>
<%= fields_for :sources do |s| %>
<%= s.input :your_column %>
<% end %>
<%= f.button :submit %>
<% end %>顺便说一下,已经有很多问题了,这就是所谓的“嵌套表单”
https://stackoverflow.com/questions/43644585
复制相似问题