Found the following answer:
Ruby / MySQL fetching single row but still using .each?
No loop necessary. Just call first on Mysql2::Result
local_var = row.first['Path']
سؤال
learning ruby (or trying.)
I'm using the Mysql2 gem to query data that I know will only return one record (LIMIT 1.) However, Mysql2 returns a Mysql2::Result which I have to iterate to get my value:
client2.query("SELECT `Parent_ID`,`Path` FROM `Categories` WHERE (`ID` = 83) LIMIT 1").each do |row|
local_var = row['Path']
end
Of course, local_var is not in scope so this method doesn't set the variable to use outside of the loop in the rest of the script.
It shouldn't be this hard. :)
Thanks!
المحلول
Found the following answer:
Ruby / MySQL fetching single row but still using .each?
No loop necessary. Just call first on Mysql2::Result
local_var = row.first['Path']
نصائح أخرى
Your question is how to get a Model instead of an array of models?
ModelIf you need the name:
Category.find(83).name
Array of models
If you need the name of each one:
# Find by the ID
Category.all.each do |result|
result.name
end
# Find by one attribute
Category.find_all_by_cod(83).each do |result|
result.name
end