2012-02-13 120 views
1

這是user.rb:功能,但實際上沒有可用

# == Schema Information 
# 
# Table name: users 
# 
# id   :integer   not null, primary key 
# name  :string(255) 
# email  :string(255) 
# created_at :datetime  not null 
# updated_at :datetime  not null 

class User < ActiveRecord::Base  
    attr_accessible :name, :email, :password, :password_confirmation, :remember_token 
    has_secure_password 
    before_save :create_remember_token 

    validates :name, presence: true, :length => { maximum: 50 } 
    valid_email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 
    validates :email, :presence => true, 
        :format  => { with: valid_email_regex }, 
        :uniqueness => { case_sensitive: false } 

    validates :password, length: { minimum: 6} 

    private 

    def create_remember_token 
     self.remember_token = SecureRandom.urlsafe_base64 
    end 
end 

我已經定義了功能create_remember_token,但我注意到,在這個文件中,我不能把它。在Rails的控制檯中,它也沒有工作:

1.9.2-p290 :002 > User.first.create_remember_token 
    User Load (0.4ms) SELECT "users".* FROM "users" LIMIT 1 
NoMethodError: private method `create_remember_token' called for #<User:0x0000010289cda0> 
    from /Users/luke/.rvm/gems/ruby-1.9.2-p290/gems/activemodel-3.2.0/lib/active_model/attribute_methods.rb:404:in `method_missing' 
    from /Users/luke/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.2.0/lib/active_record/attribute_methods.rb:129:in `method_missing' 
    from (irb):2 
    from /Users/luke/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.0/lib/rails/commands/console.rb:47:in `start' 
    from /Users/luke/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.0/lib/rails/commands/console.rb:8:in `start' 
    from /Users/luke/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.2.0/lib/rails/commands.rb:41:in `<top (required)>' 
    from script/rails:6:in `require' 
    from script/rails:6:in `<main> 

我在做什麼錯?

+0

您嘗試調用的方法是私有方法,因此您無法在創建的類之外調用它。解決這個問題的方法是從您定義方法的類中刪除private關鍵字(User.rb) – mohamagdy 2012-02-13 09:17:10

+0

請問您爲什麼更改了接受的答案?只是好奇... – Mischa 2013-09-17 07:40:52

回答

1

注意到你得到的錯誤:NoMethodError: private method。將方法移至private以上,您就可以訪問它。

0

您只能在班級本身中調用私人方法,而不能從班級以外調用。將你的方法上面private

def create_remember_token 
    self.remember_token = SecureRandom.urlsafe_base64 
end 

private 

# Your private methods here 
0

如果您的問題是在控制檯中調用此方法,那麼是從私有中刪除它將解決問題。但是,我想你一定要保持這種方法的私密性。還有其他一些潛在的問題嗎?失敗的測試?該方法應該正常工作。

相關問題