user938363
user938363

Reputation: 10350

Rails 4.2: How to force to reload model definition?

There is a model payment_request.rb in our Rails 4.2 app and we would like to force to reload it with before_action in its controller payment_requests_controller.rb. Is there a way doing reloading?

Upvotes: 3

Views: 5133

Answers (3)

Amal Kumar S
Amal Kumar S

Reputation: 16045

If you want to reload the model class you can use this

ModelClassName.reset_column_information

API Documentation on reset_column_information

Upvotes: 3

twonegatives
twonegatives

Reputation: 3438

@Mariah suggested you a way to reload an instance of a model class, but in case your intention was to really reload the definition of a class, you could do it with this trick:

before_action :reload_model

def reload_model
  Object.send(:remove_const, :PaymentRequest)
  load 'app/models/payment_request.rb'
end

Beware of side effects like impossibility to access a PaymentRequest from other parts of same instance of your application during that class is reloading. Actually I doubt if doing this in your controller code is a right thing.

Reloading a class may be useful when some constant value should be updated (as it is filled upon first class loading and changed during time). But in case this situation occurs during your application is live, you'd better consider changing constant-based solution to something more appropriate.

Upvotes: 4

Mariah
Mariah

Reputation: 62

You want the model to reload when? Not sure why you would want a reload on a before_action, you can simply just call "@payment_request.reload" in any method

If you want it in a before action you would have to add this before_action in your controller. you will also have to define a function that it calls. For example,

before_action :reload

def reload 
    @payment_request.reload
end

Upvotes: 0

Related Questions