2017-05-17 17 views
0

我在我的應用程序中有一個頁面,用戶在其中選擇一個運輸選項。我需要將他們的選擇添加到數據庫中的order.total。我在order.rb模型下面的自定義方法:用simple_form在rails中調用提交模型方法

def update_order_from_shipping_page(shipping) 
    new_total = self.total + self.shipping 
    self.update_attributes(total: new_total) 
end 

在我看來,以下形式:

%= simple_form_for @order, url: charges_update_order_path(:shipping), method: :post do |f| %> 
    <div class="row"> 
     <div class="form-inputs text-left"> 
     <div class="form-group col-sm-6"> 
      <%= f.collection_radio_buttons :shipping, shipping_choices, :first, :last, item_wrapper_class: :block_radio_button_collection %> 
     </div> 
     </div> <!-- form inputs --> 
    </div> <!-- choices row --> 
    <div class="row"> 
    <%= f.button :submit, "Calculate Shipping" %> 
    </div> 
    <% end %> 

我創建了以下路線:

post 'charges/update_order' 

我有這在我的charges_controller

def update_order 
    @order = current_order 
    if @order.update_order_from_shipping_page(shipping) 
     redirect_to new_charge_path and return 
    else 
     redirect_to :back 
     flash[:notice] = "Something is amuck." 
    end 
    end 

正確填充單選按鈕並且不顯示控制檯或服務器錯誤,但charges#new頁面上顯示的總數不反映模型方法會觸發的更新。任何人都可以看到我要去哪裏嗎?

+0

創建一個操作並提交給它。 http://stackoverflow.com/a/7507925/4643970 –

+0

@MahmoudSayed,謝謝你的參考!我更新了OP,但仍然沒有看到模型方法生效。 – Liz

回答

1

你的方法接收的參數(shipping),但它是不使用它:

def update_order_from_shipping_page(shipping) 
    new_total = self.total + self.shipping 
    self.update_attributes(total: new_total) 
end 

new_total被添加到self.shippingself.total,而不是添加shipping。所以,除非self.shipping已經包含任何數據,否則不會添加任何內容。

其結果是,當你調用與方法:

@order.update_order_from_shipping_page(shipping) 

它沒有考慮到shipping並沒有更新total完成。

要修復它,改變update_order_from_shipping_page方法,因此增加了self.shippingshipping代替:

def update_order_from_shipping_page(shipping) 
    new_total = self.total + shipping 
    self.update_attributes(total: new_total) 
end 

UPDATE

爲了避免Array can't be coerced into BigDecimal,你需要從選項正確的值Array並將其轉換爲Integer/Float。爲了實現這個目標更新您的控制器的update_order方法:

def update_order 
    @order = current_order 
    shipping = params[:order][:shipping].gsub(/[$,]/,""​).to_f # new line added 

    if @order.update_order_from_shipping_page(shipping) 
    redirect_to new_charge_path and return 
    else 
    redirect_to :back 
    flash[:notice] = "Something is amuck." 
    end 
end 
  • gsub(/[$,]/,""​)是消除貨幣字符($,

  • to_fString轉換爲Float

+0

非常棒!不幸的是,現在我得到了'Array不能被強制轉換成BigDecimal',因爲我在視圖中傳遞了':shipping',這就是我的所有運輸選項。如何讓它傳遞用戶在表單上選擇的值? – Liz

+0

@Liz你如何在'if @ order.update_order_from_shipping_page(shipping)'中設置'shipping'的值? – Gerry

+0

完整的表單在OP上,但它現在是'<%= simple_form_for @order,url:charges_update_order_path(:shipping),方法:: post do | f | %>'...我知道這是不正確的,但我不知道如何得到在形式選擇的值... – Liz

相關問題