2012-02-04 2 views
0

사용자가 링크를 클릭하여 다른 열에 표시 할 때마다 특정 노트에서 노트 제목을 검색하려고합니다. 제발 루비/레일에서 여전히 초보자입니다. 내 index.html.erb 분명히해시에서 수집하고 html로 표시하는 RoR

<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> 

, 잘못된 메신저하고 뭔가 내 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 

에서

.

+0

당신이'내부 script' 태그를 작성하는 이유는'div'가 의도하는 것은 대체 .. 'script' 태그가 대체되면서 처음에는 작동하지 않고 다음 번에는 작동하지 않을 것입니다. – rubyprince

+0

감사합니다. 지금 편집 할 것입니다. 편집 : 실제로, div id를 표시하려고했는데, div 안에 javascript가 있어도 몇 번의 클릭으로 작동했습니다. –

+0

괜찮아요 .. 그래서 div.now에 표시하려고하는 당신은 div의 내용으로 노트 레코드의 ID의 배열을 보내고 있습니다. – rubyprince

답변

1

야, 즉 (

현재 변형 해결하려면 잘못된 코드입니다 : [ 'ID']

모든 <퍼센트 = 노트의 첫번째 = @notes_hash을 || [] %>를 출력 노트 값 단지 스크립트에서, 그래서 <퍼센트 노트 = @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

그것이 나쁜 코드라고 생각했습니다. 나는 당신의 다른 솔루션을 좋아했습니다. 당신이 당신의 대답을 바꿀 수 있다면 어떨까요? –

+0

감사합니다! 여전히 루비/레일을 배우고 이것은 많은 도움이됩니다! –

관련 문제