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?
thx for your help in advance
About the state attribute, it would be better to use an
after_initializecallback to set the default instead of overriding the initialize function :To properly override a function you should pass params and args this way :
Notice that there is often a better way than using this !