Rails not loading application.html.erb, instead loading view stubs - ruby-on-rails

My application.html.erb is a classic file with the <%= yield %> statement. The expected would be if I went to domain.com/controller/action that it yields to the view in the appropriate directory. Instead, it's pulling up just the view (the correct view, but without the application wrapper). (There's no other layouts other than application)
This is my second rails application. The other one went smoothly, but this one is giving me one problem after another. I rtfm'd and googled and came up with nothing. I even rebooted webrick, though I didn't restart apache (proxypass to webrick), as I thought that overkill. Not to mention we host some low-volume websites.
The strangest thing is, when I call the root ie: domain.com it calls application.html.erb and yields to the home view.
I did use scaffolding, but it was my understanding that calling script/generate scaffold simply builds files and doesn't configure anything except routes. Which I already fixed.
Things I thought might help answer question. Let me know if you need more.
Devel logs where it's obvious that layouts application isn't loading:
domain.com
Processing HomeController#index (for 24.20.194.187 at 2009-09-03 15:24:15) [GET]
Parameters: {"action"=>"index", "controller"=>"home"}
ESC[4;35;1mCompany Columns (2.6ms)ESC[0m ESC[0mSHOW FIELDS FROM `companies`ESC[0m
ESC[4;36;1mCompany Load (0.4ms)ESC[0m ESC[0;1mSELECT * FROM `companies` WHERE (`companies`.`subdomain` = 'slate') LIMIT 1ESC[0m
Rendering template within layouts/application
Rendering home/index
ESC[4;35;1mUser Columns (2.6ms)ESC[0m ESC[0mSHOW FIELDS FROM `users`ESC[0m
ESC[4;36;1mUser Load (0.4ms)ESC[0m ESC[0;1mSELECT * FROM `users` WHERE (`users`.`id` = '2') LIMIT 1ESC[0m
domain.com/users
Processing UsersController#index (for 24.20.194.187 at 2009-09-03 15:24:03) [GET]
Parameters: {"action"=>"index", "controller"=>"users"}
ESC[4;36;1mCompany Columns (2.6ms)ESC[0m ESC[0;1mSHOW FIELDS FROM `companies`ESC[0m
ESC[4;35;1mCompany Load (0.4ms)ESC[0m ESC[0mSELECT * FROM `companies` WHERE (`companies`.`subdomain` = 'slate') LIMIT 1ESC[0m
ESC[4;36;1mUser Columns (2.7ms)ESC[0m ESC[0;1mSHOW FIELDS FROM `users`ESC[0m
ESC[4;35;1mUser Load (0.4ms)ESC[0m ESC[0mSELECT * FROM `users` ESC[0m
Rendering users/index
ESC[4;36;1mSQL (0.2ms)ESC[0m ESC[0;1mSET NAMES 'utf8'ESC[0m
ESC[4;35;1mSQL (0.2ms)ESC[0m ESC[0mSET SQL_AUTO_IS_NULL=0ESC[0m
application.html.erb [edited element contents]:
Oh right. less than greater than. suffice it to say, it has the html, head, and body tags, with a <%= yield %> statement.

First confirm that the only file in views/layouts is application.html.erb, then double check your UsersController and make sure that any line specifying the layout is removed.

Related

Rails Inconsistent database results

I have a Rails application where there is a request to create elements on a table and another one, waiting, that reads if such element was created or not.
Right now, I check the live Data and the waiting process never sees any new record for the table.
Any ideas how to force a reconnection or anything that will update the model reference?
The basic idea:
One user, through a POST, is creating a record (that i can see directly on the database).
Another piece of code, that was running before the requests, is waiting for that record, but does not find it.
I'd appreciate any insights.
The waiting request is probably using the ActiveRecord cache. Rails caches queries for the duration of a request, so if you run the exact same query multiple times in the same request, it will only hit the database the first time.
You can simulate this in the console:
Entity.cache { Entity.first; Entity.first }
In the logs, you'll see something like this (notice the second request says CACHE):
[2018-12-06T10:51:02.436 DEBUG (1476) #] Entity Load (4.9ms) SELECT "entities".* FROM "entities" LIMIT 1
[2018-12-06T10:51:02.450 DEBUG (1476) #] CACHE (0.0ms) SELECT "entities".* FROM "entities" LIMIT 1
To bypass the cache, you can use:
Entity.uncached { Entity.where(key: #key)&.last }
Using uncached will disable the cache inside the block, even if the enclosing scope is running inside a cached block.
It seems that, for a running Rails application, if a running piece of code is looking for anything that has been updated by a new request, after the first began its execution, the updated data would not show, using active_record models.
The solution: Just run a raw query.
sql = "SELECT * FROM entities WHERE key = '"+key+"' ORDER BY ID DESC LIMIT 1;"
records_array = ActiveRecord::Base.connection.execute(sql).values
I know it's a huge oversimplification and that there is probably an underlying problem, but it did solved it.

Why is Ruby on Rails executing `SELECT 1 AS one` queries?

I'm getting into a project in Ruby on Rails currently, which I don't really have any experience in. Now, we're running into some performance problems that I think are related to executing too many queries.
We have a Service model that we set in our controller as follows:
#services = Service.includes(:points).with_points
The with_points scope is defined in the service as such:
scope :with_points, -> { joins(:points).where.not(points: []).distinct }
(I think the where clause is not needed here, but that's probably not relevant to the question.)
Then in the view, we're using the fetched services, with linked points, as follows:
<% #services.each do |s| %>
<div class="col-xs-12 col-sm-6 col-lg-4 serviceDiv" data-rating="<%= s.service_ratings %>" >
<% if s.service_ratings == "A" %>
<% grade = "rating-a" %>
<!-- etc. -->
Now, as far as I've seen when researching around, this is a relatively normal pattern when trying to list all rows from a table. However, when I look at the logs, it looks like a separate query is executed for every service?
# This query is what I'd expect:
SQL (1.6ms) SELECT DISTINCT "services"."id" # etc, etc
# But then we also get one of these for every service
Service Exists (1.5ms) SELECT 1 AS one FROM "services" WHERE "services"."name" = $1 AND ("services"."id" != $2) LIMIT $3
# And quite a few of these for every service:
CACHE Service Exists (0.0ms) SELECT 1 AS one FROM "services" WHERE "services"."name" = $1 AND ("services"."id" != $2) LIMIT $3
Now, my hunch is that those "Service Exists" lines are bad news. What are they, and where are they coming from? Is there anything else that's relevant that I'm missing here?
After #MarekLipka's pointers in the comments on this question, I managed to find the source of the problem. Not sure how many people will run into this setup in the future, but I'll share it just in case.
The clue was in our accessing s.service_ratings which was not, in fact, a column in the database. ActiveRecord Query Trace pointed to the source of all those queries being a reference to s.service_ratings in the view, which was a red flag.
service_ratings was actually a method (assuming I'm using the correct terminology here) on the Service model that, apart from returning a value based on a calculation on several of the model's properties, also called self.update_attributes to actually store that value in the database. This meant that every time we retrieved this model's data in order to display it, we also ran another query to save that value to the database - often redundantly.
In other words, the solution for us now is to either run the calculation at some other point of time and store it in the database once, or recalculate it every time we need it and not store it at all.

ActiveRecord requerying depending on order of operations

New to Ruby and Rails so forgive me if my terminology is off a bit.
I am working on optimizing some inherited code and watching the logs I am seeing queries repeat themselves due to lines like this in a .rabl file:
node(:program) { |user| (!user.programs.first.nil?) ? user.programs.first.name : '' }
user and program are both active record objects
Moving to the rails console, I can replicate the problem, but I can also get the expected behavior, which is only one query:
>u = User.find(1234)
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE [...]
> (!u.programs.first.nil?) ? u.programs.first.name : ''
Program Load (0.2ms) SELECT `programs`.* FROM `programs` [...]
Program Load (0.3ms) SELECT `programs`.* FROM `programs` [...]
=> "Output"
Note that repeating the ternary statement in the console will always give me 2 queries.
I can get the expected behavior like so:
> newu = User.find(12345)
User Load (3.8ms) SELECT `users`.* FROM `users` WHERE [...]
> newu.programs
Program Load (0.6ms) SELECT `programs`.* FROM `programs` [...]
> (!newu.programs.first.nil?) ? newu.programs.first.name : ''
=> "Output"
Repeating the ternary statement now won't requery at all.
So the question is: why does calling newu.programs change the behavior? Shouldn't calling u.programs.first.nil? also act to load all the program records in the same way?
With an association, first is not sugar for [0].
If the association is loaded, then it just returns the first element of the array. If it is not loaded, it makes a database query to load just that one element. It can't stick that in the association cache (at least not without being smarter), so the next query to first does the query again (this will use the query cache if turned on)
What Rails is assuming is that if the association is big, and you are only using one element of it then it would be silly to load the whole thing. This can be a little annoying when this isn't the case and you are just using the one item, but you're using it repeatedly.
To avoid this you can either assign the item to a local variable so that you do genuinely only call first once, or do
newu.programs[0]
which will load the whole association (once only) and return the first element.
Rails does the same thing with include?. Instead of loading the whole collection, it will run a query that tests whether a specific item is in the collection (unless the collection is loaded)

MongoDB redundant queries on system.namespaces collection?

So I've been using MongoDB (with the Mongoid Ruby Gem) for a while now, and as our app has grown I've noticed requests taking longer and longer as my data has grown, here is what a typical request for my app looks like, but it takes about 500ms, just for the DB stuff.
Nothing special here just some controller stuff:
Started GET "/cities/san-francisco?date_range=past_week" for 127.0.0.1 at 2011-11-15 11:13:04 -0800
Processing by CitiesController#show as HTML
Parameters: {"date_range"=>"past_week", "id"=>"san-francisco"}
Then the queries run, but what I don't understand is that for every query that runs it performs a MONGODB dashboard_development['system.namespaces'].find({}) before actually running it! Why?
MONGODB dashboard_development['system.namespaces'].find({})
MONGODB dashboard_development['users'].find({:_id=>BSON::ObjectId('4e80e0090f6d2e306f000001')})
MONGODB dashboard_development['system.namespaces'].find({})
MONGODB dashboard_development['cities'].find({:slug=>"san-francisco"})
MONGODB dashboard_development['system.namespaces'].find({})
MONGODB dashboard_development['accounts'].find({:_id=>BSON::ObjectId('4e80e0090f6d2e306f000002')})
MONGODB dashboard_development['system.namespaces'].find({})
MONGODB dashboard_development['neighborhoods'].find({"city_id"=>BSON::ObjectId('4e80e00a0f6d2e306f000005')})
Then the views get rendered, they are pretty slow too... but that is a seperate problem all together, I'll address that at another time.
Rendered cities/_title_and_scope.html.erb (109.3ms)
Rendered application/_dropdown.html.erb (0.1ms)
Rendered application/_date_range_selector.html.erb (6.2ms)
Rendered cities/show.html.erb within layouts/application (122.7ms)
Rendered application/_user_dropdown.html.erb (0.9ms)
Rendered application/_main_navigation.html.erb (5.8ms)
So minus the views the request took about 500ms, thats too long for a really simple query, additionally the app is going to grow and that time is going to grow as well. Also this example is faster than the requests usually take, sometimes it takes 1000ms or more!
Completed 200 OK in 628ms (Views: 144.9ms)
Additionally I wanted to ask what fields are most appropriate for indexes? Maybe this is my problem, as I'm not really using them at all. Any help understanding this would be really really appreciated. Thanks!
You need to use indexes -- otherwise, your mongo queries are executing what is best described as a full table scan. It is loading the entirety of your collection's json documents into memory and then evaluating each one to determine if it should be including in the response.
Strings, Date, Numbers can all be used as index -- the trick is, have an index on each attribute you are doing a "where" on.
You can turn off table-scans in your mongo config to help find table scans and destroy them!

How see the converted sql from ActiveRecord method in view, etc

I will be happy if someone clear doubt, I can see objects in view by
using <%= debug #object %> and lot of methods is there apart from view
like .to_yml, etc
Is there any method available for seeing the converted sql from
ActiveRecord method in view, etc. Although I can find it in console but
it will confuse when we run multiple queries..
example:
User.find :all
it will produce
SELECT * FROM users;
in output console
But i want it in view are any other specific point like yml , etc ?
This great gem will privide you with the info you're looking for plus many others:
https://github.com/brynary/rack-bug
It consists in a debug bar at the top of each page in development.
In rails 3 you can call to_sql on a relation
User.where(:name => :bob).to_sql # => "SELECT `users`.* FROM `users` WHERE (`users`.`name` = 'bob')"
You can render that into a view or anywhere else you like.

Resources