简体   繁体   中英

How I can invoke rails callback from separated script with ActiveRecord?

I have a simple rails app with active record model and callback inside.

class Place < ApplicationRecord
  after_update :update_markers

  private

  def update_markers
    …
  end
end

I also have separated script which have access to my bd through 'active_record'

 require 'active_record'

 ActiveRecord::Base.establish_connection({
   adapter: 'postgresql',
   encoding: 'unicode',
   username: 'postgres',
   host: 'localhost',
   database: 'myapp_development'
 })

 class Place < ActiveRecord::Base
   self.table_name = “places”
 end

 Place.last.update(name: ‘My name’)

When I try to update values inside this script callback doesn't call. How I can invoke it?

Be sure to load your model inside your script require [root]/app/models/place.rb . Right now it looks like you are not extending your model, but just define it, so there will be no callback there. Rails autoload models, but your script has no idea about it.

If your script is fully separate from your Rails app, then you have no other choices, then just to duplicate your model callback. In your script:

class Place < ActiveRecord::Base
  self.table_name = “places”
  after_update :update_markers

  private

  def update_markers
   …
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM