Reputation: 27
I'm attempting to seed the db using model methods but it isn't populating the fields correctly. First off, my seed data looks like this:
5.times do
@battery = Battery.create
end
pan1 = Pan.create(battery_id: Battery.first.id, date: '2019-01-02', reading: 8.0, amount: nil, advisement: 700, acceptance: 87.5)
15.times do
Pan.create(battery_id: Battery.first.id, date: pan1.date += 3.days, reading: Pan.reads, amount: Pan.ratings, advisement: Pan.advise, acceptance: Pan.accept, accepted: nil)
end
Now the first problem I'm seeing in the database from this is that panel1 is being created, however, reading, acceptance are both showing nil instead of the preset values I have tried to define. Where is my error in this? Here all the methods that are being used in the model:
class Pan < ApplicationRecord
belongs_to :battery
def self.reads
@pans = Pan.all
@pans.each do |pan|
if pan.reading == nil && pan.date >= 1.week.ago
pan.update_attributes!(reading: rand(5.0..18.0))
else
pan.update_attributes!(reading: nil)
end
end
end
def self.ratings
@pans = Pan.all
@pans.each do |pan|
pan.update_attributes!(amount: rand(200..20000))
end
end
def self.advise
@pans = Pan.all
@pans.each do |pan|
if pan.reading != nil && (pan.reading < 9.0 || pan.reading > 14.0)
pan.update_attributes!(advisement: rand(200..20000))
end
end
end
def self.accept
@pans = Pan.all
@pans.each do |pan|
if pan.reading != nil && pan.amount != nil
accepted = pan.amount/pan.reading
elsif pan.reading != nil && pan.advisement != nil
accepted = pan.advisement/pan.reading
end
pan.update_attributes!(acceptance: accepted)
end
end
end
I'm attempting to update attributes one at a time through each method, then calling it in the seed file. Is this a good way to go about doing it?
The two questions I have from this is why pan1 isn't seeding correctly, when I create just panel1 by itself, reading and acceptance are set to their predefined values, but when I add the 15.times do, they get set to null?
Secondly, in self.reads, I'm attempting to update that field only if it's been over a week since the last reading, and only if that field is nil. Is there a better way to write this?
Upvotes: 0
Views: 61
Reputation: 1951
One problem is that all the class methods self.reads
self.ratings
self.advise
self.accept
end with the result of an each
method, the result of an each is always the original array and you're trying to assign an array in this fields reading: Pan.reads, amount: Pan.ratings, advisement: Pan.advise, acceptance: Pan.accept
Second problem is that all those methods update all the records of Pan
model, so when you call the 15.times
block, this methods update the original result of pan
Upvotes: 2