2016-10-17 5 views
1

申し訳ありませんが、私はRails開発の新しい相対性です。私はUIのユーザーの選択に応じてRailsオブジェクトを表示したいと思っています。動物や動物園の質問を簡略化して、...リダイレクトせずにRailsオブジェクトをレンダリングするにはどうすればよいですか?

私には「たくさんの動物がいる」という動物園のためのRailsモデルがあります。親子関係。

特定の動物園のショーページでは、ユーザーがドロップダウンボックスから関連する動物を選択し、その動物のオブジェクトの詳細を同じページに表示することができます。これを行う簡単なレール方法がありますか?それともJavascriptをRailsの変数とするために苦労する道を歩かなければならないのですか?

ご協力いただきありがとうございます。大変感謝しております。

+1

これは、AJAXの素晴らしい組み込み処理を使用して、レールアプリケーションで簡単に実行できます。しかし、説明はかなり広範囲にわたっていますので、ドキュメントを読むことをお勧めします。 http://guides.rubyonrails.org/working_with_javascript_in_rails.htmlには開始方法に関するチュートリアルがあります。 – Ozgar

答えて

0

私は...ここに任意の方法は、私のsloutionだ、そのようなタスクを達成するための方法が、Ajaxを

PSを考えることができなかったあなたが任意のコードを提供しなかったので、私はいくつかの仮定をしなければなりませんでした...動物園と動物の両方が名前で1つの属性のみ

  • 動物の情報は、あなたが資産パイプライン、coffescriptとturbolinks 5を使用しているunorderdリスト
  • で提示されるだろうしていること

    • あなたは動物の選択メニュー、そして動物の情報リストを持っているあなたの動物園/ show.html.erbを更新する必要があり

    第一。あなたはそれをスキップしている場合は、show.json.jbuilderというファイルを見て、あなたの動物を持っている必要があります

    アプリ/ビュー/動物園/ show.html.erb

    <p> 
        <strong>Name:</strong> 
        <%= @zoo.name %> 
    </p> 
    <br> 
    <p> 
        <strong>Animal:</strong> 
        <%= select_tag "animals", options_from_collection_for_select(@zoo.animals, "id", "name"), id: 'select_animal', prompt: "Select Animal to view its info" %> 
    </p> 
    
    <div id="animalInfo"> 
        <ul> 
        <li><strong>Name: </strong><span id="animalName"></span></li> 
        <li><strong>Created at: </strong><span id="animalCreated"></span></li> 
        <li><strong>Updated at: </strong><span id="animalUpdated"></span></li> 
        </ul> 
    </div> 
    

    セカンド次のステップに、他にそれを作成し、次のコードを入れて...

    json.partial! "animals/animal", animal: @animal 
    

    第三には、解説のためのコードの中を見て、あなたの動物園スクリプトに次のコードを追加しますイオン

    アプリ/資産/ JavaScriptの/ zoos.coffe

    ready = -> 
        $('#animalInfo').hide() # hides the animal's info div 
        $('#select_animal').change -> # listen to changes in the animals select menu 
        if $(this).val() 
         animalId = $(this).val() 
         output = undefined 
         $.ajax #calls the animal object but its id 
         url: '/animals/'+ animalId + '.json', 
         type: 'GET', 
         dataType: 'json', 
         async: false 
         complete: (jqXHR, textStatus) -> 
         success: (data, textStatus, jqXHR) -> #return a json animal object 
          # You can call any object attribute the same way with ruby 
          # Like this: data.attribute 
          # Edit this part to adapt with your code 
          $('#animalName').text(data.name) 
          $('#animalCreated').text(data.created_at) 
          $('#animalUpdated').text(data.updated_at) 
          $('#animalInfo').slideDown() 
         error: (jqXHR, textStatus, errorThrown) -> 
        else 
         $('#animalInfo').slideUp() # hides the animal's info div if no animal selected 
    $(document).on('turbolinks:load', ready) 
    

    私はあなたがあなたに適応するために、上記のコードを微調整する必要があると思うが、コンセプトは同じになり、それがお役に立てば幸いです。

  • 関連する問題