我正在寻找一种更干的方法来迭代一些代码。我有一个User
模型,我希望在Users
模型中保留一定数量的ReportRecord
(用于报告)。
我有一个我要记录的User.names
值的已定义列表(即" Jan"," Lisa"," Tina") 。如何使这个代码更干,因为列表比三个值长得多?
@users = User.all
@users.each do |u|
# this part repeats with different names
quantity = u.where("name = ?", "Jan").count
ReportRecord.create(:user_id => u.id, :name => "Jan", :quantity => quantity)
# repeated code with different name
quantity = u.where("name = ?", "Lisa").count
ReportRecord.create(:user_id => u.id, :name => "Lisa", :quantity => quantity)
# repeated code with different name
quantity = u.where("name = ?", "Tina").count
ReportRecord.create(:user_id => u.id, :name => "Tina", :quantity => quantity)
end
答案 0 :(得分:3)
我会先对所有用户求和(1个查询而不是3个):
git pull
答案 1 :(得分:2)
names = %w(Jan List Tina)
names.each do |name|
count = User.where(name: name).count
ReportRecord.create(name: name, quantity: count) # I don't understand `u.id`
end