3

I am working on a simple application using Roda Ruby gem and Sequel. I want Sequel to return a single result as a array rather than a Model object type. When there is more than one item, it returns an array but when there's only one, it returns a Model item.

For example, in app.rb

get 'pizza' do
  @pizza = Pizza.first #=> returns object type Pizza, i want this to be a array as well
end

get 'pizzas' do
  @pizzas = Pizza.first(10) #=> returns an array of the first 10 results. 
end

If I could get a array instead of an Object type in the first case, I could use the same template for both. Otherwise it will be a bit of a hassle. Any help would be appreciated.

hetre85
  • 39
  • 8
B A
  • 1,089
  • 2
  • 14
  • 24
  • I never worked with Sequel. Just out of curiosity: What happens if you use `Pizza.first(1)`? – spickermann Jul 02 '16 at 07:02
  • Oh boy, it worked. thanks @spickermann ;) – B A Jul 02 '16 at 07:10
  • Something is wrong with the question. `Pizzas.first(10)` does not return a `Hash`, it returns an `Array` of up to 10 `Pizza` objects. If that's what you want, then all is good, but the terms could do with changing in the question. – Neil Slater Jul 02 '16 at 07:22
  • 1
    my bad, yeah sorry it does return an array. i will correct that. but still i wanted it to return a collection rather than an object. the solution in the correct answer still holds true :) – B A Jul 02 '16 at 07:25
  • OK, that makes more sense. It is also possible to get hash forms of objects from Sequel, so it is important to make that clear. Thanks for editing the question. – Neil Slater Jul 02 '16 at 07:27

1 Answers1

3

Just use first with an argument to trigger the array syntax. This works even when the argument is just 1:

Pizza.first(1)
B A
  • 1,089
  • 2
  • 14
  • 24
spickermann
  • 100,941
  • 9
  • 101
  • 131