2012-01-13 124 views
2

我想实例化一个模型对象,指定一些属性。例如如何实例化具有属性的模型对象?

post = Post.new 

应该设置post.vote_total为0。我试图做到这一点的初始化方法,但似乎它不工作:

def initialize() 
    vote_total=0 
end 

预先感谢您。

回答

7

传递一个属性的散列的对象,如:

post = Post.new(:vote_total => 123, :author => "Jason Bourne", ...) 

如果你是新的Ruby on Rails的,你可能会想读Getting Started Guide,其中涵盖这和许多有用的Rails成语在一些细节。

+0

好的,谢谢你,是的,我用这个作为例子,但是如果我想做更复杂的instanciations,比如我希望Vote.new(post)应该自动增加post_total的post? – user1144442 2012-01-13 14:21:50

+0

在这种情况下,在Vote模型上创建一个方法可能更有意义,比如Vote.add_post(post),而内部的'add_post'方法可以增加vote_total。 – MrDanA 2012-01-13 14:24:09

2

我会用回调: Available Callbacks

class Post 
    before_save :set_defaults 

    def set_defaults 
     self.vote_total ||= 0 
     #do other stuff 
    end 
end 
0

你可以让数据库来存储默认值,你

class AddColumnWithDefaultValue < ActiveRecord::Migration 
    def change 
    add_column :posts, :vote_total, :integer, :default => 0 
    end 
end 

或现有表:

class ChangeColumnWithDefaultValue < ActiveRecord::Migration 
    def up 
    change_column_default(:posts, :vote_total, 0) 
    end 
    def down 
    change_column_default(:posts, :vote_total, nil) 
    end 
end 

有但关于storing default values in the database的辩论很多。

相关问题