我觉得Rails教程结束的地方有一大步,我可以用它来做我需要的事情。这表现在这个相对简单的案例中:
我想要一个接收输入并计算音量的页面。理想情况下,这可以通过AJAX实现,因为当一个简单的页面让我重新加载它时,它总是让我恼火。
我一直在IRB中这样做:
radius = 25; length = 0.15;( radius**2) * Math::PI * length *1e-3
# radius in microns, length in meters, answer in microliters
但是混乱只是来自这里。我知道我必须路由一个页面,我知道我的控制器负责指导正确的响应,但我的计算应该在哪里发生?如何捕获表单的响应?
我似乎不明白如何整合所有这些东西......
这是我的观点(呈现,但我似乎无法将信息输入或输出:
<h2>Here I'll calculate the dead volume of a piece of tubing for you.</h2>
<%= form_tag url_for(:method => :get), :remote => true, :id => 'calculation_entry' do %>
<div id="internal_diameter">
<label for="diameter">Enter the internal diameter:</label>
<%= text_field_tag :diameter %>
<label for="diameter_unit"></label>
<%= select_tag :diameter_unit, options_for_select({
"Microns" => 'micrometers',
'inches' => 'inches'
}) %>
</div>
<div id="length">
<label for="length">Enter the length of tubing:</label>
<%= text_field_tag :length %>
<label for="length_unit"></label>
<%= select_tag :length_unit, options_for_select({
"meters" => 'meters',
"inches" => 'inches'
}) %>
</div>
<%= submit_tag "Calculate!" %>
<% end %>
<div class="output">
<span>The volume of the tubing parameters entered is:</span>
<%= @object %>
</div>
这是我建立的控制器:
class PagesController < ApplicationController
def index
end
def dead_volume
@object = Object.new
end
def calculate
@object = params.inspect
end
end
答案 0 :(得分:3)
以下是我如何使用jQuery UI实现自动完成功能的示例。阿贾克斯。它可以帮助您确定如何根据您自己的应用程序需求执行此操作。
注意:这是在Rails 3.0.X下完成的。可能有其他/更好的方法来做到这一点。
查看/布局:强>
<div id="search">
<%= form_tag('/<my_controller>/search', :method => :get, :id => "#search-text") do %>
<input type="text" name="search" value="" id="search-text" placeholder="Search">
<input type="submit" value="Go" class="button">
<% end %>
</div>
JavaScript(注意:使用jQuery UI):
$(document).ready(function() {
$("#search-text").autocomplete({
source: function(request, response) {
$.getJSON("/<my_controller>/autocomplete", {
search: request.term
},
response);
},
minLength: 2,
select: function(event, ui) {
this.value = ui.item.value;
return false;
},
});
});
<强>路线:强>
match '/<my_controller>/autocomplete' => '<my_controller>#autocomplete', :via => :get
<强>控制器:强>
respond_to :json, :only => [:autocomplete]
def autocomplete
@model = Model.autocomplete(params[:search])
render(:json => @model)
end
我希望这可以帮助你顺利前进。