将Javascript变量传递给Rails部分

时间:2013-01-31 23:43:42

标签: jquery ruby ajax ruby-on-rails-3 unobtrusive-javascript

我是Rails的新手,我正在努力完成一项显而易见的任务。 我有一个(剥离)形式:

<%= form_for @order, html: { :class => 'form-inline' } do |f| %>
  <fieldset>
  <legend><%= params[:action].capitalize %> Order</legend>

  <table class="table">
    <thead>
      <tr>
        <th><%= f.label :symbol %></th>
        <th><%= f.label :price %></th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td><%= f.text_field :symbol, class: 'input-small' %></td>
        <td><%= f.text_field :price, class: 'input-small' %></td>
      </tr>
    </tbody>
  </table>

  <div id='here'></div>

  <%= f.submit "Submit", class: "btn btn-primary" %>

  </fieldset>
<% end %>

<%= link_to 'Get quote', view_quote_orders_path, remote: true %>

当我点击“获取报价”并且符号文本字段失去焦点时,我想在div $(#here)中在Google财经中呈现报价。 我已经编写了代码来在Ruby中提取引号。

在routes.rb中,我添加了:

  resources :orders do
    get 'view_quote', on: :collection
  end

在order_controller.rb中,我添加了:

def view_quote
  respond_to do |format|
    format.js { render :layout => false }
  end
end

并在view_quote.js.erb中:

sym = $('.orders #order_symbol').val();
$('#quotes').html("<%=j render 'googlequote', symbol: sym %>");

并在_googlequote.html.erb中(我将把逻辑提取引用):

<%= symbol %>

错误在view_quote.js.erb中,因为sym未定义。 如果我用第二行替换:

$('#quotes').html("<%=j render 'googlequote', symbol: 'just_a_test' %>");

部分渲染,但我当然不需要它。 如何将javascript变量sym传递给部分_googlequote.html.erb? 否则,有没有更好的方法来实现我的目标?

3 个答案:

答案 0 :(得分:3)

你不能把它放在erb中,因为erb是在服务器上呈现的。实现此目的的一种方法是将符号用作view_quote的参数,因此您可以使用以下内容:

$('#quotes').html("<%=j render 'googlequote', symbol: params[:sym] %>");

(当然,你可以更好地连接那个参数,但这是一个很好的起点)。

答案 1 :(得分:1)

您正在Orders集合上发出GET请求。这意味着所有这些。如果要使用订单模型中的符号,请在成员上发出请求。

否则你可以将它作为参数传递(我认为你正在尝试做)。如果您想在每次更改时将其传递给服务器,我建议使用jQuery change方法。然后你可以发一个ajax请求:

$.get('/orders', { sym: $('.orders #order_symbol').val() }, function(response) {
   $('#here').html(response);
});

在控制器中:

def view_quote
  @sym = params[:sym]
  # use @sym in rendering partial
end

答案 2 :(得分:1)

谢谢@ ben-taitelbaum和@ajcodez,最后我使用了另一种方法,在excellent article的例子4和RyanonRails中的评论中提出。

通过这种方式,在捕获符号字段更改事件之后,符号将传递到控制器,在该控制器中实现逻辑(从谷歌财务中抓取报价)。结果再次传递给json格式的javascript以插入布局。

相关问题