2012-12-18 35 views
0

我想在我的模特里使用Devise的current_user幫手,這樣我就可以用before_saveDress模型中保存Shop的貨幣。如何在模型中使用current_user?

這是行不通的:

# Dress model 
before_save :set_currency 

def set_currency 
    self.currency = current_user.shop.currency 
end 

它在控制器工作:

def create 
    @dress = current_user.shop.dresses.create(params[:dress]) 
    @dress.update_column(:currency, current_user.shop.currency) 
end 

但似乎效率不高,因爲它會在UPDATECOMMIT做。 StackOverflow上的其他用戶表示current_user不應在模型中使用。有沒有其他方式可以訪問模型中的current_user

回答

1

使用.build代替.create在控制器設定值到衣服模型的貨幣屬性。

def create 
    @dress = current_user.shop.dresses.build(params[:dress]) 
    @dress.currency = current_user.shop.currency 
    if @dress.save 
     ..... 
    else 
     ..... 
    end 
    end 
1

的一種方法是給用戶作爲參數傳遞到模型的方法,並且不使用before_save回調

# Dress model 

def set_currency(user) 
    self.currency = user.shop.currency 
end 

另一種方法是專門設置的貨幣。由於貨幣是Dress'字段,因此您可以使用當前用戶貨幣在您的表單上放置一個隱藏字段,該字段將作爲參數傳遞給您的創建操作,並且會爲您透明地保存。

如何實現它:

# At your Dress form, in your View 
    <%= f.hidden_field :currency, :value => @user.shop.currency %> 

    # At your controller 
    def create 
     @user = current_user 
    end 

這樣,你就不必做任何事情來挽救貨幣。它會傳遞參數來創建Dress,你只需要確保currency是一個ActiveRecord字段。

通常,在特定的時間將您的應用程序的狀態這類知識附加到您的模型上並不好。如果你發現自己處於一種絕對確信你需要這種行爲的情況下,停下來問問自己是否真的有意義。

在這個例子中,我真的覺得(在不知道你的應用程序的情況下)貨幣應該是表單中的隱藏字段,因爲這是你的模型必須存在的東西,它確實是一個字段,因此與模型參數一起傳遞是有意義的。

問候

+0

我無法獲得第一個解決方案。我如何將用戶傳遞給該方法? –

1

我會建議只是處理的控制器設置他們,但......

如果你不介意違反MVC了一下,這裏有一個辦法做到這一點:

# application_controller.rb 
before_filter :set_current 
def set_current 
    User.current = current_user 
end 

# app/models/user.rb 
cattr_accessor :current 

# app/models/dress.rb 
before_save :set_currency 
def set_currency 
    self.currency = User.current.shop.currency 
end 
相關問題