Rails server reduce verbosity? - ruby-on-rails

One method of debugging within the Controllers I have learnt from Django is to actually print out variables within the controllers itself. However, I realize that this method is not as practical in rails as the default rails webserver is pretty verbose and it's making me difficult to trace.
FYI I read about the rails debugging page but most of those debug techniques exist in the VIEW layer (like <% #myvar.debug %>). I want to be able to see the state of vars inside the controllers and I don't want to use the rails debugger as it's kind of an overkill for something so simple.
My question is: is there a variable that I can set to reduce statements like those below from being produced at each page serve?
Started POST "/submissions" for 127.0.0.1 at 2011-06-02 02:35:38 -0400
Processing by SubmissionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"U+I2mSfCRFvOyT/L82TTzsVRVJQuJbB+X3SaMWr/IM4=", "submission"=>{"url"=>"http://wasdvasd.com", "receiver_id"=>"1", "comment"=>"asdvasdvasdv"}, "commit"=>"Create Submission"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Link Load (0.1ms) SELECT "links".* FROM "links" WHERE "links"."url" = 'http://wasdvasd.com' LIMIT 1
AREL (0.3ms) INSERT INTO "links" ("url", "created_at", "updated_at") VALUES ('http://wasdvasd.com', '2011-06-02 06:35:38.399463', '2011-06-02 06:35:38.399463')
AREL (0.2ms) INSERT INTO "submissions" ("link_id", "author_id", "receiver_id", "comment", "visited", "created_at", "updated_at") VALUES (5, 1, 1, 'asdvasdvasdv', NULL, '2011-06-02 06:35:38.402094', '2011-06-02 06:35:38.402094')
Redirected to http://localhost:3000/submissions
Completed 302 Found in 244ms

You should be able to change the logging level in your config/environments/*.rb files.
See: http://guides.rubyonrails.org/debugging_rails_applications.html#log-levels for the different log levels.

Related

many cache calls in development log - how to prevent them

I have a Rails 4.2 app that has literally hundreds of calls like this:
CACHE (0.0ms) SELECT "albums".* FROM "albums" WHERE (albumable_type='ItemProfile' and albumable_id=33333) ORDER BY "albums"."id" ASC LIMIT 1
CACHE (0.0ms) SELECT COUNT(*) FROM "assets" WHERE "assets"."album_id" = $1 AND "assets"."is_enabled" = $2 [["album_id", 19182], ["is_enabled", true]]
CACHE (0.0ms) SELECT "albums".* FROM "albums" WHERE (albumable_type='ItemProfile' and albumable_id=33333) ORDER BY "albums"."id" ASC LIMIT 1
CACHE (0.0ms) SELECT "assets".* FROM "assets" WHERE "assets"."album_id" = $1 AND "assets"."is_enabled" = $2 ORDER BY "assets"."position" ASC LIMIT 1 [["album_id", 19182], ["is_enabled", true]]
Two questions:
Are these calls actually being made (my understanding is no due to "CACHE")?
Is there a way to tell Rails that it already has this info and doesn't need to check for it? Like hundreds of times seems liek a bug on my end
edit #1
so the problem is that there is stuff like the following:
def instore_image
album.enabled_assets.first
end
and
def image_600w
Rails.logger.info("#9797 here is instore_image_url")
instore_image.asset.url(:fixed_width600)
Rails.logger.info("#9898 here is instore_image_url")
end
The image_600w is calling a round of sql calls (whether cached or not). It seems like to prevent this from happening I need to set an instance variable on the object.
You should check out the section on Caching with Rails in Rails Guides:
1.5 SQL Caching
Query caching is a Rails feature that caches the result set returned
by each query so that if Rails encounters the same query again for
that request, it will use the cached result set as opposed to running
the query against the database again.
So these queries are actually being made by your application, however ActiveRecord intercepts these queries and prevents SQL query by directly delivering from Query cache.
Is there a way to tell Rails that it already has this info and doesn't need to check for it? Like hundreds of times seems liek a bug on my end.
Yes, Rails is already doing the best it can by reusing cached query results. You can use bullet to identify N+1 queries and other similar inefficient database usage patterns in your application.

Attribute not updated in production

Rails version: 4.2.3
I am into a strange situation here, I think it is a silly thing, but I dont know why this happens.
I receive a post notification on a URL, something like /accounts/payment. After process the json I received, I need do a update on a attribute of model Account. I am doing something like this:
account.update_columns(status: "delayed")
or update_attributes
everything works fine locally. All tests pass. But for a unknown reason when this code run in production, the attribute is not updated.
here some logs from production env.
SQL (1.7ms) UPDATE "accounts" SET "status" = 'delayed' WHERE "accounts"."type" IN ('StandardAccount') AND "accounts"."id" = $1 [["id", 94]]
Account.find(94).status
Account Load (0.7ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1 [["id", 94]]
=> "actived"
Thanks in advance
UPDATE 1
My modal schema is:
StandardAccount < Account
UPDATE 2
Not a Rails problem. I found a Trigger on DB involved with accounts table and cause the problem.

rails ActiveRecord transactional Integrity / Data not committing mid scenario spec?

I know i'm mis-understanding how ActiveRecord maintains integrity/works: hoping someone can clarify for me explaining why the following is not working?
We have an abnormal situation: our rails app calls a compiled binary that accesses (and creates a new table rows, it does not update existing) in a shared database. We therefore run config.use_transactional_fixtures = false in rails_helper (other wise we get savepoint errors).
The data needs to commit within the scenario so this legacy app can access the data in the database during the test.
During a test we are setting up data via eval(rubyexpression) (see below for full code)
"provider = Provider.create({:provider_reseller_phone_number => '0200000000', :provider_registered_business_name => 'ProviderReseller', :provider_name => 'providerwithzero'})"
NOTE:
i know we should be using factorygirl for this, thats a different
long story
there is no additional provider model code e.g. callbacks,
hooks are anything
using debugger to pause the test (line 22), the data is not saved to the database, but it is there once the rspec completes.
We cannot figure out why!? surely data is committed after each transaction e.g. eval?
appreciate any guidance / learnings?
we've tried
using new + "save" on the provider variable but it isn't populated by the eval.
config.use_transactional_fixtures = true but this breaks our other need e.g. external process accessing DB
searching for ways to flush (But only seems to apply to "transactions')
tried searching for ways of committing "save_points" (no luck)
provider.create!
based on ()Rails 3: ActiveRecord observer: after_commit callback doesn't fire during tests, but after_save does fire run_callbacks(:commit)
spec_test_eval.rb
require 'rails_helper'
describe 'trying to test using rails populated data for external process' do
it 'populates provider and tests external process' do
initial_data = "provider = Provider.create({:provider_reseller_phone_number => '0200000000', :provider_registered_business_name => 'ProviderReseller', :provider_name => 'providerwithzero'})"
eval(initial_data)
debugger
expect Provider.all.count.eql?(1)
# using mysql to check providers table its empty
exec_path_str = "#{EXTERNALPROCESS} 1 1"
stdop_content = `#{exec_path_str}`
end
end
test.log output
ActiveRecord::SchemaMigration Load (0.2ms) SELECT `schema_migrations`.* FROM `schema_migrations`
(0.1ms) BEGIN
(0.1ms) SAVEPOINT active_record_1
SQL (0.2ms) INSERT INTO `providers` (`created_at`, `provider_name`, `provider_registered_business_name`, `provider_reseller_phone_number`, `updated_at`) VALUES ('2014-12-27 03:33:21', 'providerwithzero', 'ProviderReseller', '0200000000', '2014-12-27 03:33:21')
(0.1ms) RELEASE SAVEPOINT active_record_1
(0.2ms) SELECT COUNT(*) FROM `providers`
(0.4ms) ROLLBACK
So it seems that its the DatabaseCleaner gem thats causing this behaviour.
Having understood truncation, transaction etc. differences (database cleaner strategies we had transaction enabled which forces the surrounding transaction and rollback. But using DatabaseCleaner.strategy = :truncation) allows each ActiveRecord action to commit to the database. At a speed cost.
Given this does slow up the tests and we only need on some special tests, now searching solutions for different strategies based on flags/attributes.

Rails 3 application speeding up

I am newbie in Rails 3.
I'm trying to find out why my page is loaded so much slow.
I am in development mode (but in production mode there is the sane picture)
There is a log:
Started GET "/inv/claims?locale=uk" for 127.0.0.1 at 2012-05-07 14:36:24 +0300
Processing by ClaimsController#index as HTML
Parameters: {"locale"=>"uk", "property"=>"inv"}
Rendered shared/_apps_list.html.erb (0.0ms)
Rendered shared/_apps_list.html.erb (0.0ms)
Rendered shared/_apps_list.html.erb (15.6ms)
Rendered shared/_apps_list.html.erb (0.0ms)
Rendered shared/_apps_list.html.erb (0.0ms)
Rendered shared/_apps_list.html.erb (0.0ms)
Rendered shared/_apps_list.html.erb (15.6ms)
Rendered shared/_apps_list.html.erb (0.0ms)
Rendered shared/_apps_list.html.erb (0.0ms)
Rendered shared/_apps_list.html.erb (0.0ms)
Rendered shared/_apps_lists.html.erb (31.3ms)
Rendered claims/index.html.erb within layouts/application (46.9ms)
Completed 200 OK in 1594ms (Views: 46.9ms | ActiveRecord: 0.0ms)
Total amount of time is 1594ms
First question: Is it really slow?
1594 - 46.9 = *1547*ms - it's a time that my page spends for some logic (not for rendering and querying).
Second question: Is the logic of application bad in that case (1547ms)?
I try to make pagination
My page logic:
I have a folder structure:
/myfolder/1/application.xml (size of any application.xml about 5Kb)
/myfolder/2/application.xml
/myfolder/3/application.xml
/myfolder/4/application.xml
/myfolder/5/application.xml
...
/folder/50/application.xml
I'm doing...
1) I am getting such information about each folder in myfolder (myfolder/1/, myfolder/2/...): folder creation or change date. I store that information in Hash.
2) Sort getting on step 1) Hash by date of creation or change
3) Getting slice of Hash using start id and step. Saving it in new Hash.
4) Iterating through Hash from step 3. For every entry reading application.xml and parsing it to hash using doc_hash = Hash.from_xml(Nokogiri::XML(f, &:noblanks).to_xml
Yes. That's a second and a half to process a page. It's too slow.
It looks like there must be some strange logic error somewhere. Spending over a second in non-activerecord, non-view processing is way too long.
I'd look pretty deeply at any loops you have and try to understand what's happening at that level.

Slow find with including multiple associations

In a Rails controller action I call
#grid = Grid.find(params[:id], :include => [:grid_properties, :grid_entities => [:entity => :properties]])
Unfortunately it takes really long. Benchmark.realtime (in development mode) tells me 1.8812830448150635, so about 2 seconds (Rails 3.0.7, Postgres 8.4).
When turning on the SQL logging I get the following for this line of code:
Grid Load (0.9ms) SELECT "grids".* FROM "grids" WHERE "grids"."id" = 2 LIMIT 1
GridProperty Load (2.5ms) SELECT "grid_properties".* FROM "grid_properties" WHERE ("grid_properties".grid_id = 2) ORDER BY row_order
GridEntity Load (1.3ms) SELECT "grid_entities".* FROM "grid_entities" WHERE ("grid_entities".grid_id = 2) ORDER BY row_order
Entity Load (3.0ms) SELECT "entities".* FROM "entities" WHERE ("entities"."id" IN (28,7,3,6,25,11,2,12))
Property Load (6.4ms) SELECT "properties".* FROM "properties" WHERE ("properties".entity_id IN (28,7,3,6,25,11,2,12))
Every database access seems to be in the low millisecond range. Why does it take so long in the end?
I guess that the time is spent on creating the object by Ruby. How many Properties are in that Grid? The time of 'SELECT FROM properties' looks relatively high.
You could further investigate the problem, if you have some functions where you could place checkpoints - logger.debug "CHECKPOINT: #{Time.now} #{caller(0).first}"
Do you have any 'on_load' callbacks, maybe?

Resources