How to " order by id " JSON with Rabl How to " order by id " JSON with Rabl json json

How to " order by id " JSON with Rabl


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.


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 , :nameend


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 @bookchild :ordered_questions do  attributes :id, :nameend

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