Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to " order by id " JSON with Rabl

I want json output order by id(child id)

Can I solve this problem ?

this is some code in my project

show.json.rabl (I used Rabl)

object @book
attributes :id , :name 

child :questions do
  attributes :id , :name
end

books_controller.rb

def show
    @book = Book.find(params[:id])
end

Sorry for my English , Thank you.

like image 734
Eakkapan Zangkaew Avatar asked Mar 04 '12 08:03

Eakkapan Zangkaew


2 Answers

It depends on your app and what you want to accomplish, but you could define a default_scope in the Question model like this:

class Question < ActiveRecord::Base
  default_scope order('id ASC')
end

Or you could define a default_scope in the Book model:

class Book < ActiveRecord::Base
  default_scope joins(:questions).order('questions.id ASC')
end

If you want eager load the questions, then use includes instead of join.

like image 76
Jack Chu Avatar answered Sep 29 '22 10:09

Jack Chu


i don't know RABL, but i think that you can just pass in a collection instead of a symbol. given, that you :question is a has_many relation on your Book class, you could just use a finder for that:

child @book.questions.order('id ASC') do
  attributes :id , :name
end
like image 22
phoet Avatar answered Sep 29 '22 09:09

phoet