我想编写一个脚本来检查相应的记录是否存在。如果不是我想删除参考记录。
我是红宝石的新手。
if Hotload.find(lead.id).exists?
leadid = Lead.find(lead.id)
leadid.destroy
end
错误消息:
ActiveRecord::RecordNotFound (Couldn't find Hotload with id=148):
app/controllers/users_controller.rb:64:in `block in leads'
app/controllers/users_controller.rb:47:in `leads'
更新:
这是完整的功能:
def leads
load_leads = []
truck_leads = []
hotload_leads = []
#I just added another route for users/:id/leads and kept users/leads because I wasn't sure if it was used anywhere else.
@leads = Lead.where(:user_id => params[:id] || current_user.id)
@leads.each do |lead|
if lead.post_type == 'load'
load_leads.push lead.type_id
elsif lead.post_type == 'truck'
truck_leads.push lead.type_id
elsif lead.post_type == 'hotload'
hotload_leads.push lead.type_id
unless Hotload.where(:id => lead.id).exists?
lead_id = Lead.find(lead.id)
lead_id.destroy
end
end
end
@saved_loads = Load.find(load_leads, :order => "#{sort_load_column + " " + sort_direction}").paginate(:page => params[:load_leads_page], :per_page => 10)
@saved_trucks = Truck.find(truck_leads,:order => "#{sort_truck_column + " " + sort_direction}").paginate(:page => params[:truck_leads_page], :per_page => 10)
@saved_hotloads = Hotload.find(hotload_leads,:order => "#{sort_load_column + " " + sort_direction}").paginate(:page => params[:hotload_leads_page], :per_page => 10)
end
立即出错
ActiveRecord::RecordNotFound (Couldn't find all Hotloads with IDs (1590, 1479, 1478, 1468, 1476) (found 4 results, but was looking for 5)):
app/controllers/users_controller.rb:62:in `leads'
答案 0 :(得分:0)
如果查看find
的{{3}},您会发现如果找不到一个或多个ID,就会出现错误。
请尝试使用where
。
if Hotload.where(:id => lead.id).exists?
lead_id = Lead.find(lead.id)
lead_id.destroy
end
答案 1 :(得分:0)
您应该将代码更改为
if Hotload.find_by(id: lead.id).blank?
leadid = Lead.find(lead.id)
leadid.destroy
end