Jak zainicjować obiekt Model w RoR?
Tworzę stronę internetową, w której chcę, aby każdy użytkownik zaczynał od pewnych wartości dla swoich atrybutów.
Oto klasa:
class User < ActiveRecord::Base
attr_accessible :name,
:email,
:goal,
:measurement,
:bmr_formula,
:fat_factor,
:protien_factor
end
W konsoli railsowej --sandbox mogę zmienić wartości. Ale chcę rozpocząć obiekt od pewnych wartości.
Na przykład chcę, aby pomiar zaczynał się od „US”, bmr_formula zaczynał się od „Katch” ... itd. Zamiast zera.
teraz wszystko zaczyna się od zera.
Przejdę do pokazania tego, co próbowałem z wynikami każdej próby.
Oto, co zadziałało:
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 >
Dziękujemy za pomoc wszystkim!
Pełna klasa:
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
Konsola:
1.9.3p125 :001 > user = User.new("US")
=> #<User not initialized>
Dół klasy:
def initialize
@measurement = "US"
# bmr_formula = "katch"
# fat_factor = 0.655
# protien_factor = 1.25
end
Konsola:
1.9.3p125 :001 > user = User.new
=> #<User not initialized>
1.9.3p125 :002 >
Dół klasy:
self.@measurement = "US"
Konsola:
SyntaxError: /Users/Nick/Code/Rails/fitness_app/app/models/user.rb:10: syntax error, unexpected tIVAR
self.@measurement = "US"
Klasa:
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
Konsola:
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