performance - Rails: How do I minimize DB hits here? Eager loading isn't applicable -


This question is probably a bit specific, but I think it's also interesting than normal POV.

Rail applications can subscribe to other users in the app. When I show a list of users, I have to check if the current user is subscribed to users in the list. If she is subscribed, then I show buttons and other ways to unsubscribe.

Because the whole thing relies on the current user, I can not use curious loading. So when I show 20 users in the list, I generate 20 additional hits on DB, which seems to be bad for me.

I am thinking of a good way to solve this problem. The best solution I have so far so far is to load the ID of users subscribing to session sessions in the session during log-ins and then check every user against the ID in the session. But it may be possible to take other issues when the user has subscribed to many people. Apart from this, I'm not sure that this is the best way to load all subscriptions, even if the user never sees the user list during this session.

The next best thing that came to my mind is the same thing, but not during login but instead when a user list is loaded.

What do you think?

You definitely should start working on a cache system. You can follow at least 3 methods, you can also add them to gain even more efficiency.

Database caching

Create a connection table to catch ID relationships between users and customers so that you do not need to calculate when you fly .

Model caching

Expensive queries can be cached.

  def find_subscribers Rails.cache.fetch ("find_subscribers_ # {Current_user}") Query # End Finish Ending  

See Caching < / Strong>

You can also cache the pieces of the scene to prevent costly expansion.

You

  • Edit: >

    You customize the query can do.

      ActiveRecord :: base.connection.execute ("SELECT count (*) as C fROM subscribers_users WHERE user_id = # {other_user id} and subscriber_id = # {self.id}")  

    may

      counter = subscribe user count (: conditions => {: subscriber_id = & gt; self.id} ,: group = & Quot; user_id ")  

    The query will return a hash where the key is user_id and the result of the value calculation then you repeat the hash instead of running a query for any record in the scene You can.


    Comments

    Popular posts from this blog

    c++ - Linux and clipboard -

    What is expire header and how to achive them in ASP.NET and PHP? -

    sql server - How can I determine which of my SQL 2005 statistics are unused? -