2013-01-31 84 views
2

我是Rails中的新成员,我在一个显然很容易的任务中挣扎。 我有一个(精简)形式:将Javascript变量传递给Rails partials

<%= 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 $在谷歌财经的报价(#这里)当我点击“获取报价”和当符号文本字段失去焦点。 我已经编写了代码来提取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

你不能把它放在erb中,因为erb是在服务器上呈现的。做到这一点的方法之一是使用符号作为一个参数去view_quote,所以你可以有这样的:

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

(当然,你可以更REST风格线了param所,但是这是一个很好的起点点)。

+0

请参阅http://stackoverflow.com/questions/5161952/rails-link-to-remote-with-params关于如何发送参数作为远程请求的一部分。 –

1

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

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

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

和Controller:

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

谢谢@奔taitelbaum和@ajcodez,最后我用了不同的方法,例如4建议这excellent article和RyanonRails其中的评论。

通过这种方式,在捕获符号字段更改事件后,符号被传递到控制器,逻辑(从谷歌金融中引用报价)被实现。结果再次以json格式传递给JavaScript以插入到布局中。