gpt4 book ai didi

ruby-on-rails - 如何使用new_record?,改变了?并坚持?本例中 Rails 中的方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:00:07 24 4
gpt4 key购买 nike

试图理解new record? , changed ?persisted ?在下面的例子中。

如何,这段代码有这样的结果:

 # NOW
# there is 0 new record after running new_data array
# there is 0 changed record(s) after running new_data array
# there is 3 persisted record(s) after running new_data array

试图得出这样的结果:

# WANT
#there is 1 new record(s) after running new_data array
#there is 1 changed record(s) after running new_data array
#there is 2 persisted record(s) after running new_data array

*问题是:*

怎么做?想记录更改和新增记录的数量。

Cars.delete_all

original_data = [
{:brand => 'Mercedes', :used => false, :year => 2000 },
{:brand => 'Honda', :used => true , :year => 2000 },
{:brand => 'Nissan', :used => false, :year => 2000 }
]

new_data = [
# updating year to 2013
{:brand => 'Mercedes', :used => false, :year => 2013 },
# new record
{:brand => 'Tesla', :used => false, :year => 2013 },
# same data
{:brand => 'Nissan', :used => false, :year => 2000 }
]


# create new cars
original_data.each do |c|
Cars.create(c)
end

# updates
persisted = 0
new_records = 0
changed_records = 0
new_data.each do |c|
car = Cars.where(:brand => c[:brand]).first_or_create
persisted +=1 if car.persisted?
new_records +=1 if car.new_record?
changed_records +=1 if car.changed?
end

puts "there is #{new_records} new record(s) after running new_data array"
puts "there is #{changed_records} changed record(s) after running new_data array"
puts "there is #{persisted} persisted record(s) after running new_data array"

*更新*

代码根据答案:- 尝试仅更改 1 条记录,而不是 2 条记录。

# updates
persisted = 0
new_records = 0
changed_records = 0
new_data.each do |c|
car = Cars.where(:brand => c[:brand]).first_or_initialize
car.assign_attributes(c)
persisted +=1 if car.persisted?
new_records +=1 if car.new_record?
changed_records +=1 if car.changed?
car.save
end

there is 1 new record(s) after running new_data array
there is 2 changed record(s) after running new_data array
there is 2 persisted record(s) after running new_data array

最佳答案

我可能不会直接回答您的问题,但我会尝试解释 Activerecord 生命周期方法。

new_record?

car = Car.new # => initialize a new Car object
car.new_record? # => true

坚持?

car.save
car.persisted? # => true

改变了吗?

car.model = 'New release model S'
car.changed? # => true

毁了?

car.destroy
car.destroyed? # => true

关于ruby-on-rails - 如何使用new_record?,改变了?并坚持?本例中 Rails 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20720901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com