我想要 id 的 json 输出顺序(子 id)
我可以解决这个问题吗?
这是我项目中的一些代码
show.json.rabl(我用的是 Rabl)
object @book
attributes :id , :name
child :questions do
attributes :id , :name
end
book_controller.rb
def show
@book = Book.find(params[:id])
end
对不起我的英语,谢谢。
我想要 id 的 json 输出顺序(子 id)
我可以解决这个问题吗?
这是我项目中的一些代码
show.json.rabl(我用的是 Rabl)
object @book
attributes :id , :name
child :questions do
attributes :id , :name
end
book_controller.rb
def show
@book = Book.find(params[:id])
end
对不起我的英语,谢谢。
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.
我不知道 RABL,但我认为你可以只传入一个集合而不是一个符号。鉴于您:question是has_many您班级的关系Book,您可以为此使用查找器:
child @book.questions.order('id ASC') do
attributes :id , :name
end
在模型中进行排序并使用 Rabl 查询排序方法
问题模型
class Question < ActiveRecord::Base
# ...
scope :by_id, order('id ASC')
# ...
end
然后在书中有一个方法
class Book < ActiveRecord::Base
# ...
has_many :questions
# ...
def ordered_questions
questions.by_id
end
# ...
end
最后,你的 Rabl 将是
object @book
child :ordered_questions do
attributes :id, :name
end