如何在RoR中初始化Model对象?

时间:2012-08-14 02:41:52

标签: ruby-on-rails

我正在创建一个网站,我希望每个用户都可以从属性的某些值开始。

这是班级:

class User < ActiveRecord::Base

  attr_accessible :name, 
              :email, 
              :goal, 
              :measurement, 
              :bmr_formula, 
              :fat_factor, 
              :protien_factor

end

在rails控制台--sandbox中,我可以更改值。但我想用某些值启动对象。

例如,我希望测量以“US”开头,bmr_formula以“Katch”开头......等等而不是nil。

现在,一切都从零开始。

我将继续展示我尝试过的每次尝试得到的结果。



以下是有效的:

after_initialize do 
   self[:measurement] = "US" 
   self[:bmr_formula] = "katch"
   self[:fat_factor] = 0.655
   self[:protein_factor] = 1.25
   puts "User has been initialized!"
end


1.9.3p125 :001 > user = User.new
User has been initialized!
=> #<User id: nil, name: nil, email: nil, goal: nil, measurement: "US", bmr_formula: 
"katch", fat_factor: 0, protein_factor: 0, created_at: nil, updated_at: nil> 
1.9.3p125 :002 > 

感谢大家的帮助!



全班:

attr_accessible :name, 
              :email, 
              :goal, 
              :measurement, 
              :bmr_formula, 
              :fat_factor, 
              :protien_factor


def initialize(measurement)                
@measurement = measurement
# bmr_formula = "katch"
# fat_factor = 0.655
# protien_factor = 1.25
  end

控制台:

1.9.3p125 :001 > user = User.new("US")
 => #<User not initialized>

班级底部:

 def initialize               
    @measurement = "US"
    # bmr_formula = "katch"
    # fat_factor = 0.655
    # protien_factor = 1.25
  end

控制台:

1.9.3p125 :001 > user = User.new
 => #<User not initialized> 
1.9.3p125 :002 > 

班级底部:

self.@measurement = "US"

控制台:

SyntaxError: /Users/Nick/Code/Rails/fitness_app/app/models/user.rb:10: syntax error, unexpected tIVAR
self.@measurement = "US"

类别:

after_initialize :measurement, 
                 :bmr_formula, 
                 :fat_factor, 
                 :protien_factor

 def defaults
   self.measurement = "US"
   self.bmr_formula = "katch"
   self.fat_factor = 0.655
   self.protien_factor = 1.25
  end

控制台:

1.9.3p125 :001 > user = User.new
 => #<User id: nil, name: nil, email: nil, goal: nil, measurement: nil, bmr_formula:    
nil, fat_factor: nil, protien_factor: nil, created_at: nil, updated_at: nil> 
1.9.3p125 :002 > user.measurement
=> nil 
1.9.3p125 :003 > user.bmr_formula
=> nil 

2 个答案:

答案 0 :(得分:6)

我会使用after_initialize回调:

after_initialize :default_values
def default_values
  self.status ||= 'P'
  self.measurement = "US"
  self.bmr_formula = "katch"
  self.fat_factor = 0.655
  self.protien_factor = 1.25
end

答案 1 :(得分:1)

你可以使用before_create进入那里并在第一次保存对象之前搞乱事物。如果你在保存它之前需要它,你可以使用before_initialize来完成类似的事情。

你也只想设置自我测量,而不是自我。@ measurement。