2012-08-15 37 views
0

數據庫中創建一個項目,我會嘗試儘可能簡單:Rails的:如何使用PARAMS與其他數據

我有獲取產品信息(名稱,說明,...等)的形式,我想添加到商店產品列表(使用模型關聯:產品belongs_to :store和商店has_many :products)。

除了這些信息之外,我還想在產品表中添加一個'ON'狀態字段。爲什麼?在產品所有者想要刪除產品的情況下,狀態變爲「OFF」而不是完全銷燬數據庫上的產品(由於統計學原因,我必須保留數據6個月)。

這是我的控制器代碼:

# Create a new product for the actual company. 
def create 

    # Get store information. 
    @store = Store.find_by_id session[:store_id] 

    # Set new store product. 
    product = @store.products.build(
     :name => params[:product][:name], 
     :desc => params[:product][:desc], 
     :url => params[:product][:url], 
     :status => 'ON' 
     ) 

    if product.save 
     redirect_to :back, :notice => 'Product successfully created.' 
    else 
     redirect_to :back, :alert => 'Something goes wrong.' 
    end 
end 

我想這個快捷方式,但它不工作:

product = @store.products.build(params, :status => 'ON') 

我的問題,是如何添加:status => 'ON'更優雅比列出所有params

在此先感謝。

回答

2
product = @store.products.build(params[:product]) 
product.status = 'ON' 
+1

我真是太棒了!感謝丹尼斯的幫助,這很明顯!絕對需要休息一下...... – htaidirt 2012-08-15 10:41:21

1

我想你可以創建一個範圍,說scope :enabled, conditions: {status: 'ON'},然後你可以做product = @store.products.enabled.build(params[:product])

+0

這是非常有趣的方法,用範圍創建。謝謝! – 2012-08-16 04:07:00

相關問題