I would like to instantiate a model object specifying some attributes. For instance
post = Post.new
should set post.vote_total to 0. I tried to do this in the initialize method but it seems it's not working :
def initialize()
vote_total=0
end
thank you in advance.
Pass an attributes hash to the object, as in:
post = Post.new(:vote_total => 123, :author => "Jason Bourne", ...)
If you're new to Ruby on Rails, you'll probably want to read the Getting Started Guide, which covers this and many more useful Rails idioms in some detail.
I would use callbacks: Available Callbacks
class Post
before_save :set_defaults
def set_defaults
self.vote_total ||= 0
#do other stuff
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With