Reputation: 211
I am using Rails 5.2.2 .I need to have simple informations from DB records.I created some simple methods in view helpers like :
def set_simple_info
"This user has #{@user.accounts.count} accounts<br>
These accounts has #{@user.accounts.relations.count} relations. <br>
#{@user.accounts.orders.count} times ordered something".html_safe
end
But this creates many SQL queries. I thought i could create some variables and manage them in Ruby way but im not sure what is the most effective way to do it.How can i get some simple informations from DB without using many SQL queries?
Upvotes: 0
Views: 37
Reputation: 1035
Define these as a helper method. But the best approach is to define them as class methods in their corresponding classes. And then call them directly.
def user_relation_count(user)
Relation.joins(account: :user).where(users: {id: user.id}).count
end
def user_orders_count(user)
Order.joins(account: :user).where(users: {id: user.id}).count
end
Upvotes: 1