我正在查询一堆表/模型以生成tab_projects
ID列表,并使用这些ID对其他表/模型中的其他记录执行操作,但我确实想要更新受影响的项目通过查询。这就是我到目前为止所做的:
_account_type_list_member_id = RefAccountType.find_by_typename('List Member').id
# Select all projects more than one week old and associated accounts not classified as a list member
_records = TabProject
.select('tab_projects.id as tab_project_id, tab_projects.name as project_name, tab_projects.tab_client_seat_id as client_seat_id, tab_clients.name as client_name, tab_accounts.screen_name')
.where("tab_projects.updated_at < '#{1.week.ago}' and tab_client_project_accounts.ref_account_type_id != #{_account_type_list_member_id}")
.joins('inner join tab_clients on tab_projects.tab_client_id = tab_clients.id')
.joins('inner join tab_client_project_accounts on tab_projects.id = tab_client_project_accounts.tab_project_id')
.joins('inner join tab_accounts on tab_client_project_accounts.tab_account_id = tab_accounts.id')
# loop through all records in recordset
_records.map do |_record|
# do some stuff
end
_records.touch
当我运行它时,我收到以下错误:
'method_missing': undefined method 'touch' for #<TabProject::ActiveRecord_Relation:0x000000084b2a00> (NoMethodError)
所以我的问题是:
touch
updated_at
查询返回的记录并保存到_records
? touch
所有涉及的记录吗?它必须是分布在tab_projects
(原始表/模型),tab_client_project_accounts
(联接表)和tab_accounts
(与tab_projects
中的任何给定记录相关联的帐户的记录{1}})?答案 0 :(得分:1)
您尝试在touch
代理上调用ActiveRecord::Relation
方法,基本上ActiveRecord::Relation
是一个位于数组顶部的图层,因此您需要调用它
_records.each(&:touch)
触摸只会将updated_at
更新为Time.current
,因此您可以使用性能非常高的update_all
自行实现此功能,这将生成适用于多条记录的数据库更新语句
_records.update_all(update_at: Time.current)
您可以在update_all
代理上致电ActiveRecord::Collection
,对于所有可用的方法,请参阅文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations