5

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

这是课程:

class User < ActiveRecord::Base

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

end

在 rails console --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 
4

2 回答 2

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
于 2012-08-14T02:46:17.347 回答
1

您可以使用 before_create 在第一次保存对象之前进入那里并弄脏东西。如果您在保存之前需要它,您可以使用 before_initialize 来完成类似的操作。

您还只想设置 self.measurement,而不是 self.@measurement。

于 2012-08-14T02:47:02.573 回答