2012-10-19 27 views
2

我是Rails,Rails_Admin和Devise的新手。好一會CURRENT_USER,我認爲應該通過設計來提供,在一個模型:模型:undefined本地變量或方法`current_user'

class Item < ActiveRecord::Base 
    attr_accessible :user_id 
    belongs_to :user, :inverse_of => :items 

    after_initialize do 
    if new_record?  
     self.user_id = current_user.id unless self.user_id 
    end         
    end 
end 

在Rails_Admin我得到:

undefined local variable or method `current_user' for #<Item:0x007fc3bd9c4d60> 

同樣的,

self.user_id = _current_user.id unless self.user_id 

我看到有一個line in config/initializers/rails_admin.rb但不確定它的作用:

config.current_user_method { current_user } # auto-generated 
+1

'current_user'只在你的控制器/視圖定義 – apneadiving

+0

謝謝你,有沒有什麼辦法讓它在型號可供選擇呢?或者這是一個安全問題? – migu

+1

模型不應該意識到這一點,這不是他們的責任 – apneadiving

回答

3

您不能在模型中引用current_user,因爲它僅適用於控制器視圖。這是因爲它在ApplicationController中定義。解決此問題的方法是在控制器中創建項目時,在Item上設置用戶屬性。

class ItemsController < Application Controller 

    def create 
    @item = Item.new(params[:item]) 
    @item.user = current_user # You have access to current_user in the controller 
    if @item.save 
     flash[:success] = "You have successfully saved the Item." 
     redirect_to @item 
    else 
     flash[:error] = "There was an error saving the Item." 
     render :new 
    end 
    end 
end 

此外,以確保您的項目不保存而不用戶屬性集,你可以把一個驗證的USER_ID。如果未設置,則項目將不保存到數據庫。

class Item < ActiveRecord::Base 
    attr_accessible :user_id 
    belongs_to :user, 
      :inverse_of => :items # You probably don't need this inverse_of. In this 
            # case, Rails can infer this automatically. 

    validates :user_id, 
      :presence => true 
end 

驗證本質上解決了您在使用after_initialize回調在模型中設置用戶時所嘗試執行的操作。保證項目不保存沒有這些信息。

+0

感謝您的全面解答。當我在管理控制檯輸入數據(有時是數百行)時,我正在使用Rails_Admin並希望設置這些屬性(而不是每次創建新行時手動選擇它)。乍一看,似乎Rails_Admin控制器不可訪問。也許有一種方法可以覆蓋它。 – migu

+0

Rails_Admin的功能更像是建立在rails之上的數據庫管理系統,而不是直接與數據庫交互。但是,這種功能只會很不幸,並且不能處理控制器中所有應用程序邏輯。 – adimitri

相關問題