【问题标题】:Touching a record触摸记录
【发布时间】:2018-06-11 17:36:16
【问题描述】:

我正在查询一堆表/模型以生成 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 #&lt;TabProject::ActiveRecord_Relation:0x000000084b2a00&gt; (NoMethodError)

所以我的问题是:

  1. 如何touchupdated_at查询返回的记录并保存到_records
  2. 有什么方法可以touch 涉及所有记录吗?它必须是分布在tab_projects(原始表/模型)、tab_client_project_accounts(连接表)和tab_accounts(与tab_projects 中任何给定记录关联的帐户)的记录?

【问题讨论】:

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


    【解决方案1】:

    您正在尝试在 ActiveRecord::Relation 代理上调用 touch 方法,基本上 ActiveRecord::Relation 是 Array 之上的一层,因此您需要调用它

    _records.each(&:touch)
    

    Touch 只会将updated_at 更新为Time.current,因此您可以使用非常高效的update_all 自行实现,这将生成适用于多条记录的数据库更新语句

    _records.update_all(update_at: Time.current)
    

    您可以在 ActiveRecord::Collection 代理上调用 update_all,有关所有可用方法,请参阅文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Polymorphic+Associations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多