I need to get an integer(@integer) from the form in my root_path, do multiplication (@integer*45) and display the result on the same page. How can I do it without any models in my application? Please, share your best practice. Thank you!
I was trying to do next:
CalculatorsController
def calculation
@integer = params[:integer]
@result = @integer*45
end
def result
end
root.rb
root :to => 'calculators#result'
resources :calculators, :collection=>{:result => :get, :calculation => :post}
calculators/result.html.erb
<% form_tag root_path, :html => {:method => :post} do %>
<%= label_tag 'integer' %>
<%= text_field_tag :integer %>
<div><%= submit_tag 'OK' %></div>
<% end %>
答案 0 :(得分:1)
只需将字段添加到表单中即可...
<% form_tag root_path, :html => {:method => :post} do %>
<%= label_tag 'integer' %>
<%= text_field_tag(:integer, @integer) %>
<% if @result.present? %>
<br>
Result is: <%= @result %>
<br/>
<% end %>
<div><%= submit_tag 'OK' %></div>
<% end %>
然后将结果渲染到您的计算中......
def calculation
@integer = params[:integer].to_i
@result = @integer*45
render :result
end
答案 1 :(得分:1)
我会用 ajax 来做,所以不需要页面刷新:
首先,更新路线,例如,您只需要两条路线,一条get
(或root
)和一条post
。
routes.rb中:
Rails.application.routes.draw do
root 'calculators#result'
post 'calculators/calculation'
end
接下来,更新您的观点:
form_tag
中的网址(改为calculation
,而不是result
)。remote: true
选项以启用 ajax 。result.html.erb:
<% form_tag calculators_calculation_url, remote: true do %>
<%= label_tag 'integer' %>
<%= text_field_tag :integer %>
<div><%= submit_tag 'OK' %></div>
<% end %>
<div id="total"></div>
并为calculation
操作创建一个视图,但由于您使用的是ajax,因此您将其创建为js.erb
并包含所需的javascript(或jQuery)以更新您的视图(我正在使用示例中的jQuery)。
calculation.js.erb:
$('#total').html('<%= @result %>')
现在,当您点击submit
时,您的表单会发送到calculation
操作,并会使用div
更新@result
。
答案 2 :(得分:0)
您的结果视图( result.html.erb )是从结果方法获取数据,而不是计算。按如下方式更新控制器:
def calculation
@integer = params[:integer]
end
def result
@result = @integer*45
end
然后,您需要一个标记来在视图中显示结果,例如:
<p> <%= @result %> </p>