6

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.

3 Answers3

4

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.

Jack Chu
  • 6,791
  • 4
  • 38
  • 44
1

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
phoet
  • 18,688
  • 4
  • 46
  • 74
0

Do the ordering in the models and use Rabl to query the ordering method

Question model

class Question < ActiveRecord::Base
  # ...
  scope :by_id, order('id ASC')
  # ...
end

and then have a method in Book

class Book < ActiveRecord::Base
  # ...
  has_many :questions
  # ...
  def ordered_questions
    questions.by_id
  end
  # ...
end

Finally, your Rabl would be

object @book
child :ordered_questions do
  attributes :id, :name
end

https://github.com/nesquena/rabl/issues/387

idrinkpabst
  • 1,838
  • 23
  • 25