[英]How to “ order by id ” JSON with Rabl
我希望json输出顺序为id(子ID)
我可以解决这个问题吗?
这是我项目中的一些代码
show.json.rabl(我用过Rabl)
object @book
attributes :id , :name
child :questions do
attributes :id , :name
end
books_controller.rb
def show
@book = Book.find(params[:id])
end
抱歉我的英文,谢谢。
这取决于您的应用程序以及您想要完成的任务,但您可以在Question
模型中定义default_scope
,如下所示:
class Question < ActiveRecord::Base
default_scope order('id ASC')
end
或者您可以在Book
模型中定义default_scope
:
class Book < ActiveRecord::Base
default_scope joins(:questions).order('questions.id ASC')
end
如果你想急切加载questions
,那么使用includes
而不是join
。
我不知道RABL,但我认为你可以传入一个集合而不是一个符号。 鉴于,你:question
是你的Book
类的has_many
关系,你可以只使用一个finder:
child @book.questions.order('id ASC') do
attributes :id , :name
end
在模型中进行排序并使用Rabl查询排序方法
问题模型
class Question < ActiveRecord::Base
# ...
scope :by_id, order('id ASC')
# ...
end
然后在Book中有一个方法
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.