I have this model
#post.rb
class Post < ActiveRecord::Base
belongs_to :user
after_initialize :create_token
attr_accessible :token
protected
def create_token
self.token = "#{Digest::MD5.hexdigest("#{self.id}")[0,4]}"
end
end
in rails c
Post.find(:all,:conditions => { :user_id => 11})
=> [#<Post id: 26, content: "<p><strong>Yao Ming</strong> (<a shape=\"rect\" title...", user_id: 11, created_at: "2011-07-12 15:08:30", updated_at: "2011-07-12 15:08:30", title: "Yao Ming", guid: "0010f6c3-040b-4e13-aa38-3a002e6f2022", contentHash: "\xB9\\\xCBK\xB0A>4\xC4~\xFC\"\xEA7\xA6y", token: "4e73">]
when the token: "4e73"
, but when I try
Post.find(:all,:conditions => { :user_id => 11, :token => "4e73"})
=> []
I get []
, why?
Post.find(:all,:conditions => { :user_id => 11}).first.token.class
=> String
Post.find(:all,:conditions => { :user_id => 11}).first.token
=> "3769"
According to Rails Guides:
The after_initialize callback will be called whenever an Active Record object is instantiated, either by directly using new or when a record is loaded from the database.
You should probably find another way to initialize this 'token' field, otherwise it will be changed every time you reload the record from database.
As Eugen says, That is the problem, In all case Rails has no native way to does that, so what you have to do is:
class Post < ActiveRecord::Base
belongs_to :user
after_initialize :create_token
attr_accessible :token
protected
def create_token
if new?
self.token = "#{Digest::MD5.hexdigest("#{self.id}")[0,4]}"
end
end
end
or simply
class Post < ActiveRecord::Base
belongs_to :user
attr_accessible :token
protected
def after_initialize
if new?
self.token = "#{Digest::MD5.hexdigest("#{self.id}")[0,4]}"
end
end
end
Well, to build an attribute based on the id
, the id
must exist. Finally, do this:
after_create :create_token
def create_token
self.token = "#{Digest::MD5.hexdigest("#{self.id}")[0,4]}"
self.save
end
I would use
before_create :create_token
so it's only generated when the record is first inserted into the database.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.