Question

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. :)

  1. Is there a way to get a single result from Mysql2 that doesn't involve a loop iteration?
  2. If not, how can I set a local variable (or some other global object value) to store the result?

Thanks!

Was it helpful?

Solution

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']

OTHER TIPS

Your question is how to get a Model instead of an array of models?

Model

If 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top