2012-03-04 8 views
6

ID(子ID)でjson出力の注文をしたいRablでJSONを呼び出す方法

この問題を解決できますか?

これは私のプロジェクトでいくつかのコード

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 

で、ありがとうございます。

答えて

4

それはあなたのアプリと何を達成したいに依存しますが、あなたがdefault_scopeを定義することができこのようなQuestionモデル:

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をロードしたい場合は、joinの代わりにincludesを使用します。

1

RABLは分かりませんが、シンボルの代わりにコレクションを渡すことができると思います。与えられた、あなた:questionがあなたのBookクラスのhas_many関係である、あなただけの、そのためにファインダーを使用することができること:

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

はい、質問は私のブッククラスのhas_many関係です ありがとう、私はそれを試しても、まだ動作しません。 –

+0

それはどういう意味ですか?結果として生じるjsonは何ですか? – phoet

+0

btw、謝罪したり、あなたの質問にあなたのものをありがとうございます。 – phoet

0

はモデルに発注を行い、発注方法

質問モデル

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しまう方法を持っているRablを使用しますbe

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

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

関連する問題