In my sample ruby apps a query like that
@ip = User.where("id = ?",@user[:user_id]).select('ip').first
returns
{"id":null,"ip":"127.0.0.1"}
And i don't want it to return id, although the id is 1, it returns is as null.
PS: it wont return id:null if i mentioned id in select like .select('id,ip')
Any help? i want just ip at return.
You may want to try pluck instead, which will return only the value you want.
ip = Model.where(conditions).pluck(:ip).first
You're misunderstanding what select does. Check out the Ruby docs to get a better understanding on how that method is used.
If all you're wanting to do is return the ip attribute from your User model based on finding a record with an id, all you need is this:
User.find(@user[:user_id]).ip
Notice that I'm using find and not where. As id should always be a unique value, there's no need to use a combination of where and first to get the single record you're looking for.
Based on your example, I'm assuming that your @user variable is an object that you created and not a instance of your User model, which is why you're accessing user_id instead of just id.
However, if it is an instance of your User model, then two things to keep in mind:
id, not user_id - and you also don't need to access it via @user[:id]. You can just do @user.id.User object that you're trying to find, then you can just get the ip from the object itself - i.e. @user.ip.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With