簡體   English   中英

Ruby on Rails-虛擬屬性

[英]Ruby on Rails - Virtual Attributes

我有以下模型:

  create_table "material_costs", :force => true do |t|
    t.string   "material"
    t.integer  "height"
    t.integer  "width"
    t.decimal  "cost",       :precision => 4, :scale => 2
    t.datetime "created_at"
    t.datetime "updated_at"
  end

如何在模型中創建虛擬屬性,以給我每種材料的每平方英寸成本?

另外,我還有另一個模型來保存增值稅值:

  create_table "taxes", :force => true do |t|
    t.string   "name"
    t.decimal  "rate",       :precision => 10, :scale => 0
    t.datetime "created_at"
    t.datetime "updated_at"
  end

如何使用此模型為每個物料提供每平方英寸的總價格,即需要增加增值稅率?

編輯 -我現在將增值稅值存儲在以下模型中:

  create_table "app_options", :force => true do |t|
    t.string   "name"
    t.string   "value"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

編輯 -這是我的控制器代碼:

  def calculate_quote
    @moulding = Moulding.find( params[:id], :select => 'cost, width' )
    @mount = MaterialCost.find(1).total_cost_per_square_mm
    @glass = MaterialCost.find(2).total_cost_per_square_mm
    @backing_board = MaterialCost.find(3).total_cost_per_square_mm
    @wastage = AppOption.find( 2, :select => 'value' )
    @markup = AppOption.find( 3, :select => 'value' )

    respond_to do |format|
      format.json { render :json => { :moulding => @moulding, :mount => @mount, :glass => @glass, :backing_board => @backing_board, :wastage => @wastage, :markup => @markup } }
    end
  end

將其放在表中實際上沒有任何意義,否則在每次更新時都需要重新計算。

正如Matchu所建議的,您應該只在模型類中定義一個方法。

注意:我添加了一個類變量來保存稅額。

class MaterialCost < ActiveRecord::Base
  # Initialize the tax rate on initialization of the class
  @@tax = AppOptions.find(:first, :name => 'VAT').value.to_f

  # ...

  def base_cost_per_square_inch
    cost / (height * width)
  end

  def total_cost_per_square_inch
    base_cost_per_square_inch * (1 + @@tax)
  end
end

和一些控制器代碼:

class MaterialsController < ApplicationController

  def calculate_full_price
    # GET /Materials/calculate_full_price/5

    # Get the material in question using the ID param.
    material = MaterialCost.find(:first, :id => params[:id])

    # Calculate the total price
    @total_price_per_sq_in_with_tax = material.total_cost_per_square_inch

    # Done (fall off to render the normal view)
  end

end

我不太確定您的稅收用例到底是什么,但這是否更有意義?

它本身並不是真正的虛擬屬性,只是一種方法,對嗎?

def cost_per_square_inch
  cost / height / width
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM