Rails: Relation with class_name does not get saved properly?
I've got a (rather simple) model representing a comment:
class Comment < ActiveRecord::Base
STATES = [:processing, :accepted, :declined]
belongs_to :note
belongs_to :author, :class_name => 'User'
validates_inclusion_of :state, :in => STATES
validates_presence_of :author
default_scope :order => 'created_at DESC'
def initialize( attributes={} )
super(attributes)
self.state ||= 'processing'
end
end
However, everytime I save a comment (with its fields set properly), the author relation always fails to save (well, actually the comment saves successfully, it just leaves out the author...). This goes as far as Comment.first.valid?
returning false
due to the validation on the author field (Comment.first.author
is nil
).
My suspicion is that I handle the default value for state-field in a wrong way? If so, how should I set the default value instead?开发者_JS百科
thx for your help in advance
About the state attribute, it would be better to use an after_initialize
callback to set the default instead of overriding the initialize function :
def after_initialize
self.state ||= 'processing'
end
To properly override a function you should pass params and args this way :
def initialize(*args,&block)
super(*args,&block)
#what-you-want-to-execute
end
Notice that there is often a better way than using this !
精彩评论