2012-02-04 29 views
0

我試圖從特定筆記本中檢索筆記標題,只要用戶單擊它的鏈接並將它們顯示在另一列中。請對我溫柔,仍然是ruby/rails的新手。RoR從哈希中收集並在html中顯示它

我static_controller.rb

def index 
    @user = current_user 
    @notebooks = @user.notebooks 
    @notes_hash = @user.notes.group_by(&:notebook_id) 

    respond_to do |format| 
     format.html 
     format.js 
    end 
    end 

我index.html.erb

<div id="notebooks-list"> 
    <% @notebooks.each do |notebook| %> 
     <%= link_to notebook.description, "#", {:class => "notebook-link", 
      :remote => true, :data => notebook.id.to_json }%> 
    <% end %> 
</div> 
<div id="notes-list"> 
    <script type="text/javascript"> 
     $(".notebook-link").click(function() { 
      var id = this.getAttribute("data"); 
      <%= notes = @notes_hash['id'] || [ ] %> 

      var notes = <%= notes.collect{ |a| a.id }.to_json %> 

      $("#notes-list").html(notes); 
     }); 
    </script> 
</div> 

顯然,即時通訊做錯了什麼。

+0

你爲什麼寫'裏面script'標籤的'div'您打算更換..它只會第一次工作,下次不會像腳本標籤被替換一樣工作。 – rubyprince 2012-02-04 07:52:26

+0

謝謝,我現在要編輯它。 編輯:實際上,我試圖顯示var id,甚至與div內的JavaScript,由於某種原因它爲幾次點擊工作。 – 2012-02-04 07:53:57

+0

好..什麼是你試圖顯示在分區..現在你正在發送筆記記錄ID數組作爲分區的內容.. – rubyprince 2012-02-04 08:04:22

回答

1

哥們,這是一個壞的代碼(

要修正電流變體:

首先<%=筆記= @notes_hash [ 'ID'] || []%>將輸出筆記值剛剛在腳本中,因此它固定到<%的債券= @notes_hash [「身份證」] || []%>

接下來你初始化變量筆記您單擊的.notebook鏈接,所以從當前程序中刪除它每次:

<div id="notes-list"> 
</div> 
<script type="text/javascript"> 
    (function() { 
     <% notes = @notes_hash['id'] || [ ] %> 
     var notes = <%= notes.collect{ |a| a.id }.to_json %> 
     $(".notebook-link").click(function() { 
      var id = $(this).getAttribute("data"); 
      $("#notes-list").html(notes[id]); # notes[id] is just an object, you will probably wants to render it someway e.g. with JQ templates 
     }); 
    })() 
</script> 

另一種方式來做到這一點只是渲染分組筆記和日常的onClick隱藏層將只顯示匹配的div:

<div id="notebooks-list"> 
    <% @notebooks.each do |notebook| %> 
     <%= link_to notebook.description, "#", {:class => "notebook-link", 
      :remote => true, :data => notebook.id.to_json }%> 
    <% end %> 
</div> 
<% @notes_hash.each_pair do |nh_id, notes| %> 
    <div class="notes-list hidden" data="<%= nh_id %>"> 
     <ul> 
      <% notes.each do |note| 
       <li><%= note. description %></li> 
      <% end %> 
     </ul> 
    </div> 
<% end %> 
<script type="text/javascript"> 
    $(".notebook-link").click(function() { 
     $(".notes-list").hide().filter("[data=\"" + $(this).attr("data") + "\"]").show() 
    }); 
</script> 
+0

認爲這是不好的代碼,但我喜歡你的其他解決方案。介意如果你能改變你的答案? – 2012-02-04 09:01:08

+0

感謝!仍然學習ruby/rails,這有助於很多! – 2012-02-04 10:04:57