2013-04-27 30 views
0

我想查詢我們的數據庫.click函數。我可以提醒(val)以便工作。但我想弄清楚如何去到數據庫中,並找出如果折扣表中的記錄存在,其中Discount.amount == VAL使用ajax查詢數據庫是否存在項目。 Rails 3

$(document).ready -> 
    $("button.discount").click -> 
    val = $('input.discount').val() 
    store = window.location.pathname.split('/')[1] 

// Would like to do something like this, I'm guessing with ajax: 

d = Discount.find_by_name(val) 
if d 
    return d.amount 
else 
    return "No discount exists" 
end 

回答

0

只需使用jQuery的$.get()方法:

$(document).ready -> 
    $("button.discount").on "click", (event) -> 
    val = $(this).val() 

    $.get 'domain/discount/?discount_value=' + val # Send the discount value as parameter 
     (data) -> 
     switch data 
      when 'ok' then do something ... 
      when 'ko' then do another thing ... 

而且在Rails控制器(假設到控制器的路徑看起來是這樣的:domain/discount/?discount_value=X

d = Discount.find_by_name(params['discount_value']) 
if d 
    response = d.amount 
    status = "ok" 
else 
    status = "ko" 

respond_to do |format| 
    msg = { :status => status, :amount => response } 
    format.json { render :json => msg } 
end 
相關問題