Reputation: 4492
I'm worried about the efficiency of this line in the controller of my Rails project
posts_list = Post.where(:title => params[:title])
If the number of "Posts" in the database grows, will the line become slow to execute? Is there any possible optimization?
Upvotes: 3
Views: 206
Reputation: 2526
Add index on title field can be a first approach :
class AddIndexTitleToPost < ActiveRecord::Migration
def change
add_index :posts, :title, uniq: false
end
end
And you can use find_each on your iteration for prevent your database growing
Post.where(title: params[:title]).find_each(batch_size: 10) do |post|
...
end
That all for applicative enhancement
Upvotes: 2
Reputation: 4617
It just fires this query,
select * from posts where title = params[:title]
You can index the title column in your migration file
add_index(:posts, :title)
Upvotes: 5