How to "order by id" JSON with Rabl

I want json output order by id (child id)

Can I solve this problem?

this is the 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, thanks.

+6
source share
3 answers

It depends on your application and what you want to execute, but you can define default_scope in the Question model as follows:

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

Or you can define default_scope in the Book model:

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

If you want to get a load of questions , use includes instead of join .

+4
source

I do not know RABL, but I think that you can just pass the collection instead of the character. what you :question are the has_many relation in your Book class, you can just use finder to do this:

 child @book.questions.order('id ASC') do attributes :id , :name end 
+1
source

Place an order in models and use Rabl to request an order method

Question Model

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

and then enter the method in the book

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

Finally, your rabl will be

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

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

0
source

Source: https://habr.com/ru/post/909926/


All Articles