【问题标题】:Is that Possible to make use of 'activerecord-import' gem for a Model-less table in Rails.?是否可以在 Rails 中为无模型表使用“activerecord-import”gem。?
【发布时间】:2015-10-15 05:11:49
【问题描述】:

我想将记录批量插入到没有模型的表中。我确实按照链接How to implement bulk insert in Rails 3 .. 除了“导入”命令外一切都很好。因为我没有模特。

我无法为该表创建一个空模型。好的,我告诉你,为什么我不能为此创建一个表。我正在使用 IOS apns 服务器进行推送通知功能。当我配置它时,它在我的数据库中创建了很多没有模型的表。在其中一个表中,我想在单个查询中批量插入记录。最初我是用循环来做的。它影响了性能。所以,我想进行优化。无论解决方案是什么,请给我任何建议。以下是我的方法。

# Push Notification to all users of the application.
  def ios_push_notification(admin_notif)
    bulk_data = []
    n = Rpush::Apns::Notification.new
    n.app = Rpush::Apns::App.find_by_name("ios_app")
    ios_user_reg_ids = UserRegId.where(:device_os=>"ios").pluck(:user_gcm_reg_id)   
    ios_user_reg_ids.each do |device_token|
      n.device_token = device_token
      n.alert = admin_notif.try(:content)
      n.data = { foo: :bar }
      bulk_data << n
    end
    p bulk_data
    Rpush::Apns::Notification.import bulk_data # I get error here, since this model does'nt exist.
  end

对不起,我的英语很差。提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord activerecord-import


    【解决方案1】:
    class Rpush::Apns::Notification
      def self.import(bulk_data)
        sql = ""
    
        until bulk_data.empty?
          row = bulk_data.pop
          sql.push("(#{row.device_token},  #{row.alert}, #{row.data})")
        end
    
        ActiveRecord::Base.connection.execute("INSERT INTO table (device_token, alert, data) VALUES #{sql.join(',')}")
      end
    end
    

    您的表格方案未知,因此请在使用前调整列。

    【讨论】:

    • 您好阿纳托利,感谢您的回答。我实施了您的解决方案,它工作正常。再次感谢..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2017-05-20
    相关资源
    最近更新 更多