2013-01-31 79 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以插入到佈局中。