Tags down


How to speed up a rails controller queries?

By : Ayaz
Date : September 15 2020, 01:00 PM
should help you out You may find help here
As @Gabbar pointed out and I will add to it, your app right now is eager-loading (opposite of lazy-loading) which means that you are loading more from the database than needed. What we need to do is optimize but that totally depends on your use-case.
code :
@users = User.all.includes(:comments) #comments for all users brought along with users but saved in RAM for future access.
@comments = @users.map(&:comments) # no need to go to db again, just RAM.
  scope :archived_customers, -> { where('archived IS false') }
  scope :potential_customers, -> { where('active IS false') }


  scope :archived_customers, -> { where(:archived => false) }
  scope :potential_customers, -> { where(:active => false) }

Share : facebook icon twitter icon

debugging a rails controller making too many queries

By : vishal kinkar
Date : March 29 2020, 07:55 AM
it should still fix some issue Are you running in development or production mode?
SHOW FIELDS FROM foo is done by your model, as you noted, so it knows which accessor methods to generate.

Rails Controller is ignoring queries

By : Hung Nguyen
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further It seems more natural to update the existing GameVote (if one exists) instead of pair delete+create.
To do so just replace:
code :
@vote = GameVote.new
@vote.game_id = params[:game_id]
@vote.vote = params[:vote]
@vote.user_id = session[:user_id]

existing_vote = GameVote.where(whatever)
@vote = GameVote.where(game_id: params[:game_id], user_id: session[:user_id]).first_or_initialize
@vote.vote = params[:vote]

Executing raw MongoDB queries in Rails controller

By : devjunpark
Date : March 29 2020, 07:55 AM
To fix the issue you can do I found a way to do it without have to establish a connection with Mongo console. Using mongoid, you can just use the update_all to generate the same query.

How do I optimize ActiveRecord queries and speed up my HAML partial which is rendered 1000 times in Rails?

By : Leila queen
Date : March 29 2020, 07:55 AM
To fix this issue Ok I got an idea from the blog I mentioned. I got it down to milliseconds! Their solution was deprecated but they also mentioned find_by_sql, which is what I used. I could create my bespoke queries and it would add additional fields to the model that were in the select clause. I'm quite disheartened that I had to un-factor my HAML templates and customize them specifically for this page, causing duplication. :( My templates were a thing of beauty and I was amazed the whole site could fit in such few lines.
code :
sql = <<-EOL
  select posts.id, posts.user_id, posts.title, ...
    (select vote from votes ...) as user_votes,
    coalesce((select sum(vote) from votes ...),0) as votes_sum,
    (select count(*) from comments ...) as comments_count
    from posts inner join users on posts.user_id = users.id
    where users.id = ?
    order by created_at desc
    limit 1000 
@posts = Post.find_by_sql [sql, (current_user ? current_user.id : -1), params[:id]]
postIds = @posts.map { |p| p.id }
sql = <<-EOL
  select tags.id, tags.tag, taggings.post_id, count(*) as count 
    from tags inner join taggings on tags.id = taggings.tag_id 
    where taggings.post_id in (?)
    group by tags.id, tags.tag, taggings.post_id
    order by count desc
@tags = Tag.find_by_sql [sql, postIds]
sql = <<-EOL
  select comments.id, comments.user_id, ...
    (select vote from votes where ...) as user_votes,
    coalesce((select sum(vote) from votes ...),0) as votes_sum,
    (select count(*) from comments ...) as has_children
  from comments
  where comments.user_id = ?
  order by created_at desc
  limit 1000 
@comments = Comment.find_by_sql [sql, (current_user ? current_user.id : -1), params[:id] ]   
$ time for i in {1..10}; do curl -I "" -H "If-None-Match: ""37d7cd0d7d37f5af51168561c2ef04e2""" -H "Accept-Encoding: gzip,deflate,sdch" -H "Accept-Language: en-US,en;q=0.8" -H "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" -H "Cache-Control: max-age=0" -H "Cookie: _Tyger_session=Y3oydVZ5OE1KMXl6cHNWL0dwNnU3bTQzNlpuaERtemRSZ3g5T3FoV2pPdEErejllVDRmME9EVGVuTkZVa1l3eDhRMmx3QXplTCtmT0xQTlFYNGhvbzJlUXVGRFc1a3BsWG1ZWThIRDE5WmVnZ2czU2NnMkRPQ0xIc1RJd3gxMm5wMUxWUEMyQUQxa1EzYzl5b3lMSDhsckd6WWJnYTJnUm96NEl4b3Q3MmdmSE1pbzE2NjF5b040SnB6TEk1WjZoSU5jYjI5V0xDSWwvMlJ3c2llOHBISmp0YlpCRGdxcnhNTWtNMXRyT3piYz0tLXdFNkpTVjFHeThTckJNNk1HU3N2NWc9PQ"%"3D"%"3D--21e668fceab201c65260d8afebce1b24728d6055" -H "Connection: keep-alive" --compressed -s | grep X-Runtime; done
X-Runtime: 0.307203
X-Runtime: 0.305202
X-Runtime: 0.313207
X-Runtime: 0.310206
X-Runtime: 0.303202
X-Runtime: 0.332220
X-Runtime: 0.312222
X-Runtime: 0.304202
X-Runtime: 0.308239
X-Runtime: 0.315209

real    0m3.449s
user    0m0.060s
sys     0m0.258s

refactoring Rails 4 before_action for code speed with reused controller methods

By : user3666388
Date : March 29 2020, 07:55 AM
will help you You asked two different questions here. A good way to abstract methods so they are resuable would be in the form of a Module or a superclass which your subclass inherits behavior from. Think of a rails model inheriting ActiveRecord::Base and how it inherits database access methods etc.
You are probably saying that you defined your before action methods in application_controller which is fine, but limiting them for use in certain controllers won't necessarily improve performance. If they are heavy and you only want them to be instantiate on certain controllers, modules would be a better way to go, but they would have to be sufficiently large and complex to gain performance in controllers that to not include them.
Related Posts Related Posts :
  • How to pass parameters into xml file?
  • Ruby Application Helper Invalid Authenticity Token
  • rake db:seed generates ArgumentError: missing keywords: from, to
  • Fastest way to remove a key from array and make it last
  • How to fix DEPRECATION WARNING: Class level methods will no longer inherit scoping from in Rails 6.1?
  • Rails seeding cities and areas tables
  • How to parse this data format in ruby
  • How to fix "String to Integer" error in Ruby
  • Use foreign key as part of composite key
  • How to fix ArgumentError: wrong number of arguments (given 0, expected 1) - RoR
  • Match parent array with child Array Seeds Ruby on Rails 5
  • How to create dates of a particular month
  • Confirmation mailers - how to avoid code duplication
  • Whats the point of ActiveRecord associations?
  • Subtracting month from date is not giving correct value in ruby?
  • PG::InvalidParameterValue: ERROR: invalid value for parameter "client_min_messages": "panic"
  • How does the upsert function in Rails work?
  • Supporting multiple params in get request in Rails
  • Why rbenv does not work on Mac OS Catalina
  • Check that array only contains string objects
  • Ruby on Rails beginner question : equality
  • Rails server exits automatically. This is what i see below:
  • Jobs pushing to queue, but not processing
  • How to share variables and functions across multiple client side JavaScript files with Webpacker in Rails 6?
  • Convert Ruby Hash to ranks with no repeats
  • Error when starting Rails Server after ruby upgrade
  • jquery auto-complete gem not working in app
  • How to use third party plugin in rails 6? Using webpacker
  • Can you specify a date range for chartkick?
  • What is the difference between "@var ||= 123" and "return @var if defined?(@var); @var = 123"?
  • Is it possible to create a single executable file of a Ruby on Rails project?
  • convert my string to comma based elements
  • RSpec: Integration test for homepage
  • How to do has_many and has_one between the same tables?
  • How to render a form (Rails Simple_form) inside of a partial?
  • How to access an instance relation using strings in Ruby on Rails?
  • How to add metadata to a csv file?
  • Is there a way to send ids to both actions in rails?
  • How to get JOIN data when using ActiveRecord::connection.exec_query?
  • Undefined method `with_indifferent_access' for #<Array: for nested model in rails
  • Does ActiveRecord handle looking up `enum`s by value when constructing the SQL query?
  • Check if multiple records exist with ActiveRecord?
  • Deadlocks in PostgreSQL when running a simple UPDATE
  • Can not upload images to a rails website, any comment for me?
  • ruby monkey patching on the fly
  • converting string attributes into date and time format
  • Getting undefined method `sorted_by' when trying to use filterrific gem on a rails app
  • <% if !current_page?(action: 'edit') %> error . No route matches {:action=>"edit", :controller=>&q
  • Can't start Ruby on Rails server
  • [undefined local variable or method `current_user' in controller]
  • How to associate 3 different models in to a 2 model relationship
  • Ruby on Rails: Use Association For Two Fields?
  • Can not create database in rails using db:migrate?
  • Disable setting attribute in FactoryBot
  • Breakpoint on a different folder in a Rails application doesn't work well
  • What's the Ruby RSpec best practice for dealing with background jobs and am I doing something needlessly complicated?
  • BUILD FAILED (OS X 10.15.1 using ruby-build 20191124) when installing ruby-2.4.0 with rbenv in OSX catalina(10.15.1)
  • How to set SameSite attribute to 'None; Secure' in Rails3.1.12 and Ruby1.9.3
  • How to use query parameter like strong parameter?
  • How to find the Client country from the Rails TCP server is getting use in Rails?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk