Rails form_tag 远程示例 [英] Rails form_tag remote example

查看:42
本文介绍了Rails form_tag 远程示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个令人难以置信的简单形式:

I have this incredible simple form:

<%= form_tag("/portal/search", method: 'get', remote: true ) do %>

  <%= label_tag(:query, 'Search for:') %>
  <%= text_field_tag(:query) %>
  <%= submit_tag("Find") %>

<% end %>
<div id="results"></div> 

我从文档中知道,我可以通过远程选项使用 AJAX:

I know from the documentation, I can use AJAX through the remote option:

<%= form_tag("/portal/search", method: 'get', remote: true ) do %>

然后我就卡住了.我知道如何在视图/部分中生成结果,但是如何在 div 元素中获取该部分?我知道一点 JQuery,所以我可以选择元素.我找到了很多结果,但他们似乎错过了我的灯泡时刻.我正在使用 Rails 4.1.6

Then I get stuck. I know how to generate results in a view/partial, but how do I get that partial inside the div element? I know a bit of JQuery, so I can select the element. I found a lot of results, but they seem to miss that lightbulb moment for me. I am using Rails 4.1.6

我的结果只是来自模型的简单记录,例如 Book(标题、作者)

My results are just simple records from a model, like Book (title, author)

感谢您的帮助!

编辑

我因为远射失分赢得了奖杯.我不得不在 view 文件夹中添加 search.js.erb 而不是资产.

I've won the cup for missing the point by a long shot. I had to add the search.js.erb inside the view folder instead of assets.

推荐答案

假设您从搜索方法中获取了 @results.

Let's say you get @results out of your search method.

在控制器中,搜索方法:

In the controller, search method:

respond_to do |format|
  format.html {render or redirect_to wherever you need it}
  format.js 
end

那么您只需要一个名为 search.js.erb 的文件,以在请求结束时运行所需的 js.它可能看起来像:

Then all you need is a file named search.js.erb to run the required js at the end of your request. It might look something like:

$('#results_div').html("<%= j @results.pluck(:title).join('<br/>') %>")

这篇关于Rails form_tag 远程示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆