简单的计算器形式
我想在 Rails 3.1 中创建一个简单的计算器表单只是为了理解。通过表格,我想获取一个数字并将其乘以二(例如)。
我已经创建了带有索引页面(/index)的控制器,然后在视图中形成:
<%= form_for @result do |f|%>
<%= f.label :number, 'Number' %>:
<%= f.text_field :number %>
<%= submit_tag 'Submit' %>
<%end%>
<%=@result%>
我需要对控制器做什么?
def index
@result = ''
end
def calculate
@result = @number.to_i*2
end
I want to create a simple calculator form in Rails 3.1 just for understanding. Via a form I want to get a number and multiplied it by two (for example).
I've created controller with index page (/index), then form in views:
<%= form_for @result do |f|%>
<%= f.label :number, 'Number' %>:
<%= f.text_field :number %>
<%= submit_tag 'Submit' %>
<%end%>
<%=@result%>
What I need to do with controller?
def index
@result = ''
end
def calculate
@result = @number.to_i*2
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是行不通的。
form_for
用于为扩展 ActiveRecord 的模型构建表单。请改用form_tag('/calculate')
。您需要定义 `match 'calculate' =>; config/routes.rb 中的“your_controller_name#calculate”。
此外,您的计算操作需要一个视图 -
calculate.html.erb
(您可以以不同的方式调用它,但必须指定render 'view_name'
。或者,如果你想使用相同的视图文件,请使用
render :action => :index
忘了提及。
要从表单访问数据,您可以使用
params[:key]
哈希。因此,在您的情况下,它看起来像
@result = params[:number] * 2
这本书是入门 Rails 的好地方。
另外,这些截屏视频也非常有帮助
This is not gonna work.
form_for
is used to build forms for models that extend ActiveRecord. Useform_tag('/calculate')
instead.You need to define `match 'calculate' => 'your_controller_name#calculate' in config/routes.rb.
Additionally, you need a view for your calculate action -
calculate.html.erb
(you can call it differently but you'll have to specifyrender 'view_name'
.Alternatively, if you want to use the same view file, use
render :action => :index
Forgot to mention.
To access the data from the form, you use
params[:key]
hash.So in your case it would look like
@result = params[:number] * 2
This book is a great place to start with Rails.
Also, these screencasts are pretty helpful too
万一其他人想要寻找 Rails 计算器的例子......我自己做了一个,一段时间后,把来自各地的小部件组合在一起。结果是一个货币计算器应用程序,它从网络获取新的汇率数据,并让您将欧元转换为您想要的货币。
对于可能也是新手并且想知道如何在 Rails 中实现计算器的人,请链接到 github:https: //github.com/Veske/form
还有一个到heroku的链接:http://harjutus.herokuapp.com
In case anyone else is going to look for rails calculator examples... I made one after some time myself now, putting little pieces together from everywhere. Result is a currency calculator app, that fetches fresh exchange rate data from the web and lets you convert euros to a currency you want.
Link to github for anyone who maybe is a total newcomer too and would like to know how to implement a calculator in rails: https://github.com/Veske/form
Also a link to heroku: http://harjutus.herokuapp.com