How could I display a *specific* user's information through an instance variable in Ruby on Rails?
This is the code I'm currently using:
profile_controller.rb:
@user = User.first :conditions => [ "lower(username) = ?", params[:id].downcase ]
show.html.haml:
.footer #{@user.bets.count} -# This displays 0, even though I can see that the user has multiple bets associated with his username in the db
My users sign in with Twitter and their usernames could be in any case variation (e.g. BOB, bob, BoB, Bob etc.) - and naturally, any information associated with their username should be accordingly displayed regardless of how the users have signed in.
One strange bug I'm running into is that all associated information with the username seems to be lost once a user signs out, and signs back in; however, this happens seemingly at random times. That is, a user can sign out and sign back in several times without issue, but once in a while, see开发者_如何学Cms to lose all associated information in the profile.
Any tips on how I could go about ensuring this isn't the case? Is the controller code I posted correct, or should I be checking for another parameter other than param[:id]
?
EDIT: Thanks for the comments, guys. It turns out that I was overwriting the user information if they just sign in with different case variations. I cleaned this up, and it works now.
Perhaps you are looking to do something like:
@user = User.where(:username => params[:username].downcase).first
You could try explicitly including the bets
when retrieving the user:
@user = User.includes(:bets).where("lower(username) = ?", params[:id].downcase).first
which will automatically retrieve all related bets.
Normally using @user.bets
it is lazy loaded, but once it is loaded, it just uses the bets
in memory. To explicitly load all bets again from database, you could also write:
@user.bets.reload.count
精彩评论