2012-12-17 42 views
1

我有一個post模型,其中has_many :comments。 每個評論(生成_comment.html.erb部分)我有一個小星形圖標,以便評論可以加星標。如何爲一個部分呈現多次的一個html代碼

我想打開一個模式窗體(引導),當用戶點擊明星。

我知道如何創建一個模態。但是,如果我將該代碼放在_comment部分中,則會針對每條評論進行渲染。

有沒有一種方式來打開每個評論的模式窗口沒有javascript(或者也許這是唯一的方式)?

_comment:

<div id="comment-#{comment.id}> 
<%= comment.content %> 
<a href="#starModal" id="star" data-toggle="modal"><i class="icon-star"> </i></a> 
</div> 

    <div id="starModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="starLabel" aria-hidden="true"> 
     <div class="modal-header"> 
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
      <h3 style="text-align: center;">Star Me!</h3> 
     </div> 
     <div id="starpop"> 
     <%= render :partial => 'layouts/star_form' , :locals => {:comment => comment,:post => post} %> 
     </div> 
    </div> 

交/ show.html.erb

<div class="post"> 

<%= @post.body %> 

<% @post.comments.each do |c| %> 
<%= render :partial=>'comment', :locals=>{:comment => c, :post => @post} %> 
<% end %> 

</div> 

是具有模態碼正確的方法,或者可以在乾燥方式(得到改進,也沒有重爲用戶(想象一下,在一個頁面中有幾百條評論......所以每個評論的數據只是一個模型的兩倍)?

+0

所以你想避免每個評論加載自己的模態股利? –

+0

yup- @ rails_has_egance這就是我想要避免的。主要是因爲我不會發帖#顯示臃腫的模式代碼 –

回答

2

如果你還沒有創建自己的資源,星星,與至少有一個「新」和「創造」的行動。 然後你的模態將成爲通過星形按鈕上的ajax onclick加載的新動作。

<%= link_to "<img src='...' />".html_safe, new_star_path, remote: true %> 

在你starscontroller新動作:

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

然後創建一個new.js.erb:

$("#place_for_modal").html("<%= escape_javascript(render 'new') %>"); 
$('#starModal').modal('show') 

讓你的模態-DIV的_new.html.erb部分。

+0

非常感謝你!現在我對軌道工作有了更多瞭解。再次感謝你! –

+1

很高興我可以幫忙;)如果您對我的回答有任何疑問,請提問。 –

相關問題