Opapadaia
Opapadaia

Reputation: 35

Rails4 : Why do I need to restart console each time I edit Model Scope?

I have a rails application and I have an Order Model that have scope today that query all orders that created today.

app/models/order.rb

scope :today, -> { where("created_at >= ?", Time.current.in_time_zone("Zone").beginning_of_day) }

and It was working fine in the console until I decided to add some functionality to this scope and edit it...

scope :today, -> { where("shift_id = ? AND created_at >= ?", 1, Time.current.in_time_zone("Zone").beginning_of_day) }

and saved then when I returned to console to test this edit, console kept giving me the same results as before edit. Until I restarted the Rails Console.

Why this behavior happens?, It made me suspect that it would affect the performance or the behavior of the app when production.

Also It made me think is it better for the app performance to split this scope to two scopes then use scope chain?

Upvotes: 0

Views: 227

Answers (2)

abhinavmsra
abhinavmsra

Reputation: 666

First let me answer why that happens. In development environment, you have spring enabled which reloads the changes and makes the web server reflect them. However, when you run a console you dont have a web server running rather just a console and hence you need to reload the console each time to make any changes.

Secondly, just because it didnt reload doesnt mean your code is less efficient. I believe you are in the early stages of development and readability and maintainability should be the priority. By that perspective, your code seems fairly good to me.

Upvotes: 0

user483040
user483040

Reputation:

You can use reload! in the console, with the caveat that it does NOT update any existing objects. So if you already did:

foo = Foo.find_by(id: 12)

Then while reload! will reload the definitions of the classes, the instance you have in hand will not be changed. You'll need to get a new instance of that object.

So to be clearer, use reload! in the console to reload your model definition, but then get a new instance of the foo object in order to see changes in attributes and/or behavior.

Upvotes: 1

Related Questions