我想为我的应用程序构建一个计算器。在用户保存记录之前,它应该能够在表单上输入一些变量并点击“计算”按钮以查看“他需要多少单位来构建”。
我创建了一个自定义路线:
get 'product_stock_calculator/:product_id', to: 'product_stocks#calculator'
型号:
class ProductStock < ActiveRecord::Base
...
end
控制器:
class ProductStocksController < ApplicationController
...
def calculator
@product_stock = ProductStock.new
@product_stock.product_id = params[:product_id]
end
...
end
查看:
product_stocks/calculator.html.erb
<%= simple_form_for(@product_stock) do |f| %>
<div class="form-inputs">
<%= f.input :product_id, label: 'Producto', collection: Product.all, required: true %>
<%= f.input :number_of_boxes, label: 'Units to build', required: true %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
如何提交表格,进行一些计算并渲染视图以显示计算结果而不保存记录?
答案 0 :(得分:0)
与你做任何事情一样。
您将表单提交到指向控制器操作的路径,您将根据参数执行计算。
例如:
routes.rb中:
match '/calculate', to "productstocks#calculate", via: 'post', as: :calculate
在您的控制器中:
def calculate
@productstock = Productstock.new(productstock_params) # strong parameters here
@result = params[:productstock][:param1] * params[:productstock][:param2] # for example
render 'calculator' # this will render with the unsaved
# new @producstock and you can use @result too in your view
end
您将表单的操作设置为calculate_path