简体   繁体   中英

In rails, how to select one specific column's data from a table? (there is only 1 row so I want only a specific result but not an array)

The table's name is Plan and it has only one row , since users are not allowed to create new data or deleted existed data. They can only edit it.

For the table, the structure is like this:

<Plan id: 1, breakfast: 100, lunch: 240, dinner: 200, ...

which means it has three different columns: breakfast, lunch, and dinner.

In a controller file, I want to access one specific column's data which user inputs, for example, the breakfast. How can I do that? Since I am quite new to rails and assume that it would be similar to:

Plan.select("breakfast")

However, I do not want the result to be an array! I want just a number so that I could use it directly in my code:

if xxxx > 90
...
end

Thank you very much!

Since there is guaranteed to be only one row, you can grab it directly via .first or .last . While you may wish to limit the selected column only to the desired breakfast with the .select() method, it probably isn't necessary and you can just retrieve breakfast from the resultant object:

Plan.last.breakfast
=> 100
# Generates this query:
Plan Load (0.4ms)  SELECT "plans".* FROM "plans" ORDER BY "plans"."id" DESC LIMIT 1

Using .select() to cause the SQL query to retrieve only the breakfast column is possible, but won't give you that much benefit other than a very tiny memory increase.

Plan.select(:breakfast).last.breakfast
=> 100
# Generates this query:
Plan Load (0.4ms)  SELECT breakfast FROM "plans" ORDER BY "plans"."id" DESC LIMIT 1

Of course, you can store it to a variable, or use it right in your expression:

if Plan.last.breakfast > 90
  # whatever
end 

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