我需要在控制器呈現爲JSON之前對Rails模型的數據執行一些基本值計算。這是一個商店的API ..產品有一個價格,屬於一家商店。在我們的價格表中,我們有一個名爲「金額」(小數)的列,用於存儲產品的成本。將模型中的值更改爲默認值
在價格模型上,我試圖做的是對所述數量進行計算,因爲我們需要添加價格邊際。
然後,在我的產品控制器中,構建查詢的位置的數量永遠不會計算,而是存儲在DB中的成本以JSON格式輸出。價格包含在使用包括的產品查詢中。目前,rails logger會拋出一個錯誤,說「NoMethodError(未定義的方法`數量爲#)」。
class API::ProductsController < ApplicationController
before_filter :authenticate_user!
def index
@department = params[:department_id]
@aisle = params[:aisle_id]
if @department.present?
@products = Product.includes(:department).includes(:aisle).where("products.store_id @> '{?}'", params[:id].to_i).includes(:price).where('prices.store_id = ?', params[:id]).references(:prices).limit(params[:max])
end
render json: @products
end
產品型號:
class Product < ActiveRecord::Base
belongs_to :store
belongs_to :department
belongs_to :aisle
has_one :price
def as_json(options)
super(:only => [:id, :name, :description, :image, :weight, :store_id],
:include => {
:price => {:only => [:amount, :store_id]},
:department => {:only =>[:name, :id]},
:aisle => {:only => [:name, :id]}
}
)
end
end
價格模型,我想做取決於量的價格計算(十進制):
class Price < ActiveRecord::Base
belongs_to :product
belongs_to :store
case self.amount
when proc {|n| n <= 1}
return self.amount * 0.15
when 115..135
return self.amount * 0.15
when 135..500
return self.amount * 0.15
end
end
在Jbuilder/Rabl的是出來的現在的問題是我的項目已接近完成,試圖回去改變/重新實施一切將花費太長時間。
'self.amount' meas,您在類「Price」上定義了一個方法'amount',而不是類的實例。 –
只是好奇。爲什麼不是數量計算,一個類的方法? – Ritikesh
是否要更改金額屬性的值?因爲有一個'write_attribute'方法可以讓你做到這一點。 'def amount =(amount)write_attribute(:amount,amount * 0.15)end' –