我为名为“Charge”的模型创建了一个脚手架,但我想从我创建的“Checkout”自定义控制器中将数据插入到模型中。
我有以下代码:
#in the routes.rb
get "checkout/pay", to: 'checkout#index'
#in the app/controllers/checkout_controller.rb
def index
@charge = Charge.new
end
#in the app/views/checkout/index.html.erb
<%= form_for(@charge, url: charges_path, method: :post ) do |f| %>
<% if @charge.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@charge.errors.count, "error") %> prohibited this charge from being saved:</h2>
<ul>
<% @charge.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="title">
<h1>shipment</h1>
</div>
<div class="large-12 columns">
<%= f.text_field :name, placeholder: "name", maxlength: "20", class: "radius" %>
</div>
<div class="large-12 columns">
<%= f.text_field :address, placeholder: "address", class: "radius" %>
</div>
<div class="large-12 columns">
<%= f.text_field :email, placeholder: "email", class: "radius" %>
</div>
<hr>
<%= f.submit "buy", class: "button green radius small expand" %>
<% end %>
#in the app/controllers/charges_controller.rb
def create
@charge = Charge.new(id: "523dd8f6aef8784386000001", amount: 60000, livemode: false, created_at: 1379784950, status: "paid", currency: "MXN", description: "Pizza", reference_id: "9839-wolf_pack", failure_code: "none", failure_message: "none", name: params[:name], address: params[:address], email: params[:email], ship_number: "5678sdf7sd5f6")
@charge.save
respond_with(@charge)
end
#in the app/models/charge.rb
validates :name, :address, :email, presence: true
为了测试,我在create方法中使用默认值填充了一些数据。 在表单('/ checkout / pay')中填写:name,:address,:email,手动处理数据,但是将我重定向到new_charge_path并告诉我: 名称不能为空 地址不能为空 电子邮件不能为空
尝试从html视图中的表单中获取参数时出现错误?
答案 0 :(得分:4)
您正在使用form_for
视图帮助程序,根据rails约定,控制器获取嵌套哈希params[:charg]
,并在表单中设置费用属性。
因此,在您的控制器上,您必须致电:
@charge = Charge.new(name: params[:charge][:name], address: params[:charge][:address], email: params[:charge][:email])