我有一个 post
模型,其中 has_many :comments
。
对于每条评论(使用 _comment.html.erb
部分生成)我都有一个小星形图标,以便评论可以加星标。
我想在用户点击星标时打开一个模态表单( Bootstrap )。
我知道如何创建模态框。但是,如果我将该代码放入 _comment
部分,它将针对每个评论呈现。
有没有办法在没有 javascript 的情况下为每个评论打开模式窗口(或者这可能是唯一的方法)?
_评论:
<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">×</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>
post/show.html.erb
<div class="post">
<%= @post.body %>
<% @post.comments.each do |c| %>
<%= render :partial=>'comment', :locals=>{:comment => c, :post => @post} %>
<% end %>
</div>
使用正确的模式代码还是可以以 DRY 方式改进它(并且对用户来说也不重(想象一下帖子在页面中有数百条评论.. 所以对于每个评论来说,只有两倍的数据一个模型?)?
最佳答案
如果您还没有创建一个自己的星星资源,至少要有一个“新建”和一个“创建”操作,怎么样? 然后你的模式将是通过星形按钮上的 ajax onclick 加载的新 Action 。
<%= link_to "<img src='...' />".html_safe, new_star_path, remote: true %>
在你的 starscontroller 中的新 Action :
...
respond_to do |format|
format.js
end
...
然后新建一个.js.erb:
$("#place_for_modal").html("<%= escape_javascript(render 'new') %>");
$('#starModal').modal('show')
让你的 modal-div 成为 _new.html.erb 部分。
关于javascript - 如何为多次呈现的部分使用一个 html 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13914788/