Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a model object with attributes?

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.

like image 552
user1144442 Avatar asked Oct 20 '25 14:10

user1144442


2 Answers

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.

like image 158
John Feminella Avatar answered Oct 22 '25 03:10

John Feminella


I would use callbacks: Available Callbacks

class Post
   before_save :set_defaults

   def set_defaults
      self.vote_total ||= 0
      #do other stuff
   end
end
like image 24
Ion Br. Avatar answered Oct 22 '25 02:10

Ion Br.