简体   繁体   English

Rails:发布后如何保存表单数据

[英]Rails: how to save form data after posting

When I use form_for :model the data is saved when I submit the form. 当我使用form_for :model时,提交表单时将保存数据。

However when I use form_tag , the data is lost after the form is processed. 但是,当我使用form_tag ,处理完表单后数据将丢失。

I need to use form_tag because I have two models in one form. 我需要使用form_tag因为我在一个表单中有两个模型。

Is there a way to save form data with form_tag ? 有没有一种方法可以使用form_tag保存表单数据?

You are making two incorrect assumptions in your question. 您在问题中做出两个错误的假设。 First, form_tag is not necessary or even recommended for multiple-model forms; 首先,对于多模型表单, form_tag不是必需的,甚至也不建议使用; Second, form_tag doesn't do anything fundamentally different from form_for , you are most likely not formatting the field names correctly for your controller. 其次, form_tagform_for并没有什么根本不同,您很可能没有为控制器正确设置字段名称的格式。

In order to create a form with nested models, you need to use the fields_for helper in conjunction with form_for . 为了使用嵌套模型创建表单,您需要结合使用fields_for帮助器和form_for The relationship needs to be defined first in the model with accepts_nested_attributes_for . 该关系需要首先在模型中使用accepts_nested_attributes_for进行定义。 Since you have not given us any information about your models, I will give you a made-up example: 由于您尚未向我们提供有关您的模型的任何信息,因此,我将举一个虚构的示例:

class Person < ActiveRecord::Base
  has_one :address
  accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
  belongs_to :person
end

This tells ActiveRecord that the Person model can accept attributes for Address, and will pass along the attributes to the correct model to be created. 这告诉ActiveRecord Person模型可以接受Address的属性,并将这些属性传递给要创建的正确模型。

<% form_for :person do |p| %>
  <% p.fields_for :address do |a| %>
    use the a form builder to create
    fields for the address model here
  <% end %>
<% end %>

chaining the fields_for helper from the p form builder lets the helpers generate attributes in the correct format. 通过从p表单构建器中链接fields_for帮助器,可以使帮助器以正确的格式生成属性。

More information: Nested Model Forms 详细信息: 嵌套模型表单

Pretty much the same way as before except you'll need to build the params. 除需要构建参数外,其他方法几乎与以前相同。 You can look at your log to see how params are being sent. 您可以查看日志以了解如何发送参数。

eg. 例如。

def create
  @silly_hat = SillyHat.new( :name => params[:name], :size => params[:size], :colour => params[:colour] )
  if @silly_hat.save
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM