Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails Active record select returns always id

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.

like image 893
Amr Ragab Avatar asked Nov 06 '25 04:11

Amr Ragab


2 Answers

You may want to try pluck instead, which will return only the value you want.

ip = Model.where(conditions).pluck(:ip).first
like image 174
Matt Avatar answered Nov 08 '25 02:11

Matt


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.


ALSO

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:

  1. you'll want to access id, not user_id - and you also don't need to access it via @user[:id]. You can just do @user.id.
  2. you don't need to find the record at all. If you already have the User object that you're trying to find, then you can just get the ip from the object itself - i.e. @user.ip.
like image 29
jeffdill2 Avatar answered Nov 08 '25 00:11

jeffdill2