Is that Possible to make use of 'activerecord-import' gem for a Model-less table in Rails.?
Asked Answered
E

1

2

I want to bulk insert records into a table, which does not have a Model. I did follow the link How to implement bulk insert in Rails 3 .. Everything was fine except the 'import' command. Because I do not have a Model.

I can not create an empty Model for that table. Okay, I tell you, why I cant create a table for that. I am using IOS apns server for Push Notification feature. When I configured that, it created lot of tables into my database without Models. In one of these tables I want to bulk insert records in a single query. Initially I did it with loop. It affected the performance. So, I wanted to have optimization. Whatever the solution is, Please suggest me anything. The following is my method.

# 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

Sorry for my poor English. Thanks in advance.

Ervin answered 24/7, 2015 at 13:39 Comment(0)
F
2
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

Your table scheme is unknown so please adjust columns before use.

Fasciation answered 25/7, 2015 at 14:57 Comment(1)
Hey Anatoly, Thanks for your answer. I implemented your solution and it works fine. Thanks once again..Ervin

© 2022 - 2024 — McMap. All rights reserved.