简体   繁体   中英

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.

您可能想尝试pluck ,它只会返回您想要的值。

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.


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 - ie @user.ip .

If you've already got the instance of a user you care about, and the IP field isn't a join to another table, then simply pull it off of the instance.

@ip = @user.ip

There's no benefit to going back to the database for information that you already have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM