I have a long complicated home page where a company is shown, for each project, information about recent events. The idea is that they have a kind of data-heavy information center from which they can monitor all activity.
I've had trouble getting this page to perform well - two days ago local load times were 4.5s(!) and they are currently at ~2.5s(!). The most alarming part about this horrible performance is that these are the load times with only 3 projects and practically no events. Performance on the live app is slightly better, but not nearly enough.
Purpose: Improve load time on home page
Here are the current queries.
# controller
#projects = #company.projects.order("project_title ASC").includes({:events => :owner}).search(params[:search], params[:page])
# view
#projects.each do |project|
#events = project.events.where(:active => true).includes(:owner).order("priority DESC")
end
Removing the .where(:active => true).includes(:owner).order("priority DESC") is shaving off 1.1 seconds on an app with only 3 projects and 4 events in total.
How should these queries be written optimally? Should indexing play a role in this case?
I've been playing around with database indexes for the looped query in the view but I haven't gotten one to cut down the time yet.
Your .includes(:events => :owners) is not doing what you think, as when you call .where on events later you have to retrieve from the data base again.
Also, if your search method is using the events and owners table you may want to used .joins() instead of .includes().
I would make sure you have indexes on every foreign key (xxx_id) and on events active.
I would also give this a shot (not sure if it works, may need some tweaking):
class Project < AR::Base
has_many :events
has_many :active_events,
:class_name => 'Event',
:conditions => {:active => true},
:order => "events.priority DESC"
:include => :owner
end
#in controller:
#projects = #company.projects.order("project_title ASC").includes(:active_events).search(...)
#in view: (abstract this to a render collection method if possible)
#project.each do |project|
#events = project.active_events
end
Related
In my views I do a lot of this:
<% cache("sports_menu_" +session[:lang], {:expires_in => 60.minutes}) do %>
...... # a load of stuff
<% end %>
However I've discovered a lot of time is spent querying the DB for data that doesn't change that often. Is there a way to cache this data in a similar manner?
For instance:
Model.find(:all, :select => "only a few fields", :conditions => "nasty conditions", :include => "some joins", :order => "date_time desc")
This takes about 7 seconds, the main table keeps about 20M records. A lot of users hit this particular action and the query only runs once/hit. But it would make sense caching that for a number of minutes so that for everyone else it will load from the cache. I'm using memcache by the way.
I can't cache the entire action because there are some parameters that change on occasion and some locale-specific code within the view.
I have considered moving that to the view level but don't feel too comfortable about that, it would kind of defeat the point of using Rails.
TIA!
It looks to me like ActiveRecord::Cache::Store is what you want. You can use it like this.
I have a Model called Person and Person has multiple posts. When I want to query post count for each person it takes a long time to process since it needs to iterate over each person and query each posts to get the aggregation.
class Person < ActiveRecord::Base
has_many :posts
end
Output (JSON):
Person1
PostsType1Count: 15
PostsType2Count: 45
Person2
PostsType3Count: 33
.
.
.
I want to calculate all the post count for each Person in a optimum way. What would be the best solution?
Here's one way to do this, if you have a small and pre-defined set of Types
class Person < ActiveRecord::Base
has_many :type_1_posts, :class_name => 'Post', :conditions => 'post_type = 1'
has_many :type_2_posts, :class_name => 'Post', :conditions => 'post_type = 2'
has_many :type_3_posts, :class_name => 'Post', :conditions => 'post_type = 3'
end
Then you can write code that looks like this to get all the data:
#all_people = Person.includes(:type_1_posts, :type_2_posts, :type_3_posts).all
The eager loading of the posts allows the count of each type of post to be available, as well as all the posts of each type.
If you need extra performance for this code, because you perform this query a lot, then you can look into using the Rails counter cache mechanism to keep track of the counts of each type on the Person object.
The beauty of Rails here is that your main display code doesn't need to change during this process of making the code faster for reading (adding a counter cache makes adding/deleting posts slower, so you may not want it in all cases).
Write initial code
Use eager loading to make it faster
Use counter cache to make it even faster
Try this May it will work for you
#In Controller
#persons = Person.all
#In View
#persons.each do |person|
person.posts.count # It will gives all posts count
person.posts.collect{|x| true if x.type==1 }.compact.count #If you want to get the post counts based on type
end
Suppose if you want to get any mehods just check in console or debug is person.methods.sort it will give all methods.
try in rails console person.posts.methods also it will give types also then check counts based on type. because i dont know which fields in posts model. so check it.
I have 2 models:
# models/car.rb
class Car < ActiveRecord::Base
belongs_to :model
end
and
# models/manufacturer.rb
class Manufacturer < ActiveRecord::Base
has_many :cars
end
When I'm executing command in rails console Car.find(1).manufacturer it shows me that one more sql query was executed SELECT manufacturers.* FROM manufacturers WHERE manufacturers.id = 54 LIMIT 1,
so I am interested is it usual (for production, first of all) behavior, when a lot of sql queries being executed just to get some object property? what about performance?
UPDATE, ANSWER:
I got an answer from another source: I was told it's "necessary evil" as a payment for abstraction
This is not a "necessary evil" and your intuition that the second query is needless is correct. What you need to do is use :include/includes to tell Rails to do a JOIN to get the associated objects in the same SELECT. So you could do this:
Car.find 1, :include => :manufacturer
# or, in Rails 3 parlance:
Car.includes(:manufacturer).find 1
Rails calls this "eager loading" and you can read more about it in the documentation (scroll down to or Ctrl+F for "Eager loading of associations").
If you always want to eager-load the associated objects you can declare default_scope in your model:
class Car
belongs_to :manufacturer
default_scope :include => :manufacturer
# or Rails 3:
default_scope includes(:manufacturer)
end
However you shouldn't do this unless you really need the associated Manufacturer every time you show a Car record.
I am working on a rails project and am having some issues with the following join:
#page = Page.find(params[:id], :joins => "LEFT JOIN page_translations ON page_translations.page_id = pages.id")
For some reason its only pulling back everything from the Pages table.
Here is my model for Page
class Page < ActiveRecord::Base
has_many :users_pages
has_many :users, :through => :users_pages
has_many :page_translations
has_many :categories
accepts_nested_attributes_for :page_translations
accepts_nested_attributes_for :categories
end
Here is my model for PageTranslation
class PageTranslation < ActiveRecord::Base
belongs_to :pages
end
Thanks in advance for all of the help!
Edit (#thenduks)
The log runs two separate queries:
Page Load (0.5ms) SELECT `pages`.* FROM `pages` WHERE (`pages`.`id` = 1) LIMIT 1
PageTranslation Load (0.5ms) SELECT `page_translations`.* FROM `page_translations` WHERE (`page_translations`.page_id = 1)
Here is what my controller looks like:
#page = Page.find(params[:id], :include => :page_translations)
I was stumped about this same thing and wasted a few hours trying to figure it out. It turns out that using the joins method of the query interface doesn't initialize the models related to the tables being joined. You can see this by watching the SQL statements in the server console, or by even redirecting ActiveRecord logging to STDOUT in your Rails console.
I was very disappointed by this. It just doesn't seem like how the joins method should work -- it certainly wasn't what I was expecting. I was expecting it to eager load, since it was in the eager load section of the Edge Guides.
Anyway, I couldn't waste any more time trying to figure it out, so what I did instead is use the fancy query interface to simply build my query, used to_sql to get the SQL for my query, and then passed the SQL to select_all, which returns an array of hashes, where each element in the array (each hash) represents a row.
Example:
query = Post.joins("LEFT JOIN categories ON post.category_id = categories.id")
query.select("posts.*, category.category_name")
con = ActiveRecord::Base.connection
results = con.select_all(query.to_sql)
Results:
[{"id": 1, "title": "joins, why have you forsaken me", "category_name": "frustration"},{"id": 2, "title": "pizza", "category_name": "food"}]
To be honest, I would still like to know for certain if it is possible to do it the way we think it should work, or the way it ought to work. Otherwise, I see no reason for having a joins method, other than to help us build the query. So if any Rails gurus out there know how to use joins to populate models related to those tables, PLEASE LET ME (US) KNOW!
Anyway, I hope this helps you move along for now.
UPDATE: So I think I just figured it out. I stumbled across this blog post. As it turns out, when using the joins method of the query interface, Rails will actually add the columns you selected from the joined tables as attribute methods of the model being joined against.
Using the same example above, I can actually access the category_name of each post by simply calling post.category_name. #$%! Unbelievably simple, but no documentation whatsoever on this!
Here it is once again:
query = Post.joins("LEFT JOIN categories ON post.category_id = categories.id")
query.select("posts.*, category.category_name")
posts = query.all
# access a post's category name
puts posts[0].category_name
# this is what I thought I would be able to do
# without Rails making another query to the database
puts posts[0].category.category_name
I hope this helps! :)
How about:
Page.find( params[:id], :include => :page_translations )
Edit:
Ok, so some time recently the behavior of ActiveRecord when it comes to joins/includes seems to have changed. The guides still refer to being able to do this though two associations, as in has_many :orders, :include => :line_items and similar... but as far as including records from a has_many... After consulting with a co-worker we came across some info on the subject. Seems that the single monolithic queries were just getting too complex and ugly and it was causing problems for some of the fancier niceties that ActiveRecord gives you and duplicate rows, that kind of thing.
TL;DR: It doesn't work like that anymore. 2 queries is expected.
I have a large central database of around 1 million heavy records. In my app, for every user I would have a subset of rows from central table, which would be very small (probably 100 records each).When a particular user has logged in , I would want to search on this data set only. Example:
Say I have a central database of all cars in the world. I have a user profile for General Motors(GM) , Ferrari etc. When GM is logged in I just want to search(a full text search and not fire a sql query) for those cars which are manufactured by GM. Also GM may launch/withdraw a model in which case central db would be updated & so would be rowset associated with GM. In case of acquisitions, db of certain profiles may change without launch/removal of new car. So central db wont change then , but rowsets may.
Whats the best way to implement such a design ? These smaller row sets would need to be dynamic depending on user activities.
We are on Rails 2.3.5 and use thinking_sphinx as the connector and Sphinx/MySQL for search and relational associations.
how about using has_many :through
class Manufacturer
class Car
class ManufacturerCarRelation
Manufacturer
has_many :manufacturer_car_relations
has_many :cars through => manufacturer_car_relations
ManufacturerCarRelation
belongs_to :manufacturer
belongs_to :car
Maybe you want to define your index with something like this:
class Car
define_index do
indexes description
has 'cars.manufacturer_id', :as => :manufacturer_id, :type => :integer
end
end
and then use field conditions, like:
Car.search "red", :conditions => {:manufacturer_id => gm.id}
or attribute filters:
Car.search "red", :with => {:manufacturer_id => gm.id}