2014-03-30 36 views
2

我遵循rails cast tutorial進行用戶驗證/註冊/登錄,這顯然具有過時的使用gem保護屬性的方法。我發現有必要切換到強大的參數,並遵循this methodRails 4 - 從受保護的屬性切換到強參數

我不得不從我的user.rb模型中刪除attr_accessible代碼(註釋如下),並想知道是否還有其他事情我應該做,而不是僅僅在控制器中定義用戶參數。現在我沒有attr_accessible或者這是不必要的,那麼用戶的字段(email,密碼,位置)是否應該有attr_accessors?我剛接觸rails,並沒有完全理解用戶認證的正確必要性。

user.rb

class User < ActiveRecord::Base 
    #attr_accessible :email, :password, :password_confirmation, :location 

    attr_accessor :password, :location 
    before_save :encrypt_password 

    validates_confirmation_of :password 
    validates_presence_of :password, :on => :create 
    validates_presence_of :email 
    validates_uniqueness_of :email 

    def self.authenticate(email, password) 
    user = find_by_email(email) 
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) 
     user 
    else 
     nil 
    end 
    end 

    def encrypt_password 
    if password.present? 
     self.password_salt = BCrypt::Engine.generate_salt 
     self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) 
    end 
    end 
end 

user_controller.rb

class UsersController < ApplicationController 
    def new 
    @user = User.new 
    end 

    def create 
    @user = User.new(user_params) 
    if @user.save 
    redirect_to root_url, :notice => "Signed up!" 
    else 
    render "new" 
    end 
    end 

    #add thing from https://stackoverflow.com/a/19130224/2739431 
    private 
    def user_params 
     params.require(:user).permit(:email, :password, :password_confirmation, :location) 
    end 

end 

回答

1

答案是相對簡單的。

請記住,當你第一次開始學習Ruby的聲明:「在Ruby中,一切都是對象」。對象具有方法,並且要訪問對象屬性,您需要一個方法accessor

attr_accessor是一種爲給定實例變量生成訪問器方法的Ruby方法(檢查attr_readerattr_writer)。
所以你的問題其實是你是否需要訪問Model以外的那些屬性。

我認爲這回答了你的問題。

重要說明attr_accessible不是Ruby方法。這是一個Rails方法,允許您將值傳遞給模型以進行批量分配:new(attrs)update_attributes(attrs)

+0

「所以你的問題實際上是你是否需要訪問這些屬性,在模型之外。」但ActiveRecord自動爲數據庫字段生成訪問器,因此「您是否需要訪問模型外的那些屬性」並不是真正的問題,因爲訪問器已經存在。 –

+0

你是對的。但是你說過數據庫字段,它們可能不是字段,而不是實例變量。確實存在差異,但我試圖變得更加通用,以便將來人們不會混淆這兩件事情。 –

1

如果有用戶的域(電子郵件,密碼, 位置)attr_accessors現在,我沒有attr_accessible還是這 不必要的?

這是沒有必要的。 ActiveRecord自動爲模型字段創建編寫者和讀者 - 這就是爲什麼您可以在User類之外使用像user.emailuser.email =這樣的方法的原因。

attr_accessor :password, :location - 我想這些是數據庫字段,對吧?你也可以刪除這一行。

+0

當我刪除該行時,我收到一條錯誤消息,說我嘗試註冊新用戶時找不到參數「password」。 – parameter

+0

好吧,一切正常,看起來像'密碼'和'位置'操作實例變量,而不是數據庫字段。 –

+0

奇怪的是,當我添加一個用於:電子郵件,然後它不會讓我創建它時登錄到帳戶。我猜是因爲它干擾了電子郵件的數據庫領域。 – parameter

相關問題