How to " order by id " JSON with Rabl
Asked Answered
P

3

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.

Prowler answered 4/3, 2012 at 8:55 Comment(0)
T
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.

Toms answered 7/3, 2012 at 8:29 Comment(0)
E
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
Envious answered 4/3, 2012 at 12:12 Comment(5)
Yes , :question is a has_many relation on my Book class , Thank you, I try it but still don't work.Prowler
what do you mean by that? what is the resulting json?Envious
btw, don't apologize or write thank you stuff to your questions.Envious
this is my sample result : njtutor.heroku.com/books/1.json , json don't sort by question id (result sort is : 56,57,58 ... 1,2,.. )Prowler
i don't think that RABL is re-ordering your result... what does @book.questions.order('id ASC').map(&:id) give you as a result?Envious
H
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

Heroworship answered 27/6, 2014 at 16:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.