触摸记录

时间:2018-06-11 17:36:17

标签: ruby-on-rails postgresql activerecord rails-activerecord

我正在查询一堆表/模型以生成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)

所以我的问题是:

  1. 我如何touch updated_at查询返回的记录并保存到_records
  2. 我可以通过某种方式touch所有涉及的记录吗?它必须是分布在tab_projects(原始表/模型),tab_client_project_accounts(联接表)和tab_accounts(与tab_projects中的任何给定记录相关联的帐户的记录{1}})?

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