這是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>
我在做什麼錯?
您嘗試調用的方法是私有方法,因此您無法在創建的類之外調用它。解決這個問題的方法是從您定義方法的類中刪除private關鍵字(User.rb) – mohamagdy 2012-02-13 09:17:10
請問您爲什麼更改了接受的答案?只是好奇... – Mischa 2013-09-17 07:40:52