在数据库中提交一个表格到2个表格 - ruby on rails
问题描述:
我有2个表格,landslides
和sources
(也许并不相互关联)。我想要一个让用户填写信息然后提交给两个表的表单。这是我目前的形式,而不sources
字段:在数据库中提交一个表格到2个表格 - ruby on rails
= 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(这是自动增量,用户不需要填写)?
谢谢!
答
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
答
您需要使用accept_nested_attributes_for
和巢相应表单:(。随着问候保留什么样的形式应该被嵌套在其中,我用源通过滑坡表单提交的例子)
在landslide.rb
accept_nested_attributes_for :sources
在您看来(我不知道HAML但不管怎么说)
<%= form_for :landslide do |f|%>
<%= f.select :start_date %>
<%= fields_for :sources do |s| %>
<%= s.input :your_column %>
<% end %>
<%= f.button :submit %>
<% end %>
顺便说一下,有很多关于这个已经,这就是所谓的 '嵌套表格'
Nested forms in rails - accessing attribute in has_many relation
谢谢。这个答案非常详细。但是我仍然收到错误'发现未经许可的参数:来源' –
如果您想调试帮助,请以此为出发点提出一个新问题。 – max
我认为这是关于来源/来源,如果山体滑坡有很多来源,我是否需要将每个来源改为来源? –