How to access Sequel result with dot operator in ruby?

158 Views Asked by At

I am newbie to Sequel and ruby and I have one thing need your help. In a word, I can't access database query result with dot operator. I am using sequel adapter in padrino ruby project. For example,

persons = Person.all
persons.each do |p|
  puts p.name . # this output correct person name, as 'john'
end

But if I do some query

persons = Person.where(:age=>20)
persons.each do |p|
  puts p.name . # this line cause error 
end

I compared their data types and there are different each other.

puts persons  # in first case - array
#<Gig:0x007fbdb6d64ef0>
#<Gig:0x007fbdb6d64838>
#<Gig:0x007fbdb6d641f8>

puts persons  # in second case - object
#<Sequel::Postgres::Dataset:0x007fbdbc614898>

So I tried to change result to hash array in second case to access fields with dot operator

persons_hash= persons.collect do |p|
  ro.to_hash
end

In this case, I was able to access user name with person[0][:name], but I couldn't access with dot operator.

So I want to know how should I have to do to access Sequel query result using dot operator.

Thanks :)

1

There are 1 best solutions below

0
nolyoly On
persons.each do |p|
  puts p.name . # this line cause error 
end

What exact error are you getting here? I'm guessing an undefined method error? Seems you may be familiar with ActiveRecord syntax. I have not used sequel myself, but it is a bit different from AR. According to their docs, you would do something like this

persons.map(:name) # => ['Harry', 'Steve', 'Israel', ...]

The all method returns an array of hashes, where each hash corresponds to a record.

For your above example, I would try the following:

persons.each do |p|
  puts p[:name] . # here we are now accessing the name hash key instead of trying to access the name method.
end

You want to access the name key of each hash being iterated over. Because you are iterating through an array OF hashes. This is why you could access that data with person[0][:name]. You were calling the 0th item of the persona array and accessing its 'name' hash key.