2013-12-17 27 views
-2

我有一個電子商務網站,在定價模型下的價格表中引用價格定價。爲每個用戶定製數據庫條目

但是,我怎麼能夠自定義價格爲個別客戶對同樣的商品。我如何使用價格模型來做到這一點。

我已經嘗試將user_id添加到表中,但似乎必須爲每個客戶端定價。我該怎麼辦?

當前表看起來像這樣;

create_table "prices", :force => true do |t| 
    t.string "country" 
    t.string "network" 
    t.decimal "price_euros", :precision => 10, :scale => 3 
    t.datetime "created_at",         :null => false 
    t.datetime "updated_at",         :null => false 
    t.decimal "price_ugx", :precision => 10, :scale => 3 
    t.decimal "price_kes", :precision => 10, :scale => 3 
    t.decimal "price_tzs", :precision => 10, :scale => 3 
    t.decimal "price_usd", :precision => 10, :scale => 3  
    end 
+0

這是不可能的幫助你,如果你不提供你的表結構和你正在嘗試做 – user65439

+0

@ user65439一些示例代碼,再次檢查 – Acacia

回答

1

實現此目的有多種方式。如果每個客戶在所有商品中都有相同的折扣,那麼您可以向用戶模型添加折扣屬性並將其應用於顯示的價格。

如果您希望每個用戶都有獨特的產品價格,那麼我會創建一個名爲UserPrice的新模型,並具有3個屬性:user_idproduct_idprice

然後,我會在我的產品模型的方法稱爲大意如下price_for_user

def price_for_user(user) 
    UserPrice.find_by_user_id_and_product_id(user.id,self.id).price 
end 

當遍歷您的產品在視圖中,你可以寫:

<%= @product.price_for_user(current_user) %> 

顯然,您需要根據您的情況需要調整變量。我還會索引UserPrice表格中的user_idproduct_id列以獲得速度。

NB如果是我,在我的控制器中,我也會考慮查找用戶的所有UserPrices並創建一個散列,然後在視圖中通過在散列中查找來顯示價格。這可能會更快。

def index 
    @products = Product.all 
    @user_prices = UserPrice.where(user_id: current_user.id).index_by(&:product_id) 
end 

在你看來:

<%= @user_prices[product.id].price %> 
+0

+1 。值得注意的是,上述更棘手(但更靈活)的變化是將用戶分配到價格組,並將價格分配給這些組。 –

+0

@Robin非常感謝...這是真實的情況,我有一個短信網關,所以我確定的目的地,並查找價格收取..目前,價格被引用爲所有貨幣的常數...我想把這些價格放在adb中,所以在數據庫中檢查目的地的價格。 Hoever,我還希望能夠根據談判爲特定用戶定製價格 – Acacia

+0

@Robin,請檢查編輯... – Acacia

相關問題