modal
這篇是關於如何在modal中使用form的筆記
#application.js
//= require bootstrap/modal
在routes中新增你想要在modal中顯示的partial
get '/games/:id/new_review', to: 'games#add_review', as: 'new_review'
然後在controller中新增respond_to,讓他可以吃js,方便使用ajax
#games controller
def add_review
@review = @game.comments.build
respond_to do |format|
format.html
format.js
end
end
然後在view中新增連結到new_review_path
<%= link_to "新增review", new_review_path(@game), {remote: true, 'data-toggle': "modal", 'data-target': '#modal-window'}%>
然後在你希望顯示出modal的view頁面新增一個div,class可以增加fade讓他有特效,但是我自己試的時候加了fade會讓jquey raty的星星出不來,所以沒有加
<div id="modal-window" class="modal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
接下來就是新增partial的頁面
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">新增評價</h3>
</div>
<div class="modal-body well">
<%= form_for [@game, @review] do |f|%>
<%= f.hidden_field :name, value: current_user.name %>
<div class="form-group">
<%= f.label :rating %>
<div id="game-rating" data-score=<%= @review.rating %>></div>
</div>
<div class="form-group">
<%= f.label :comment %>
<%= f.text_area :comment %>
</div>
<%= f.submit "送出", class: "btn btn-primary btn-xs" %>
<% end %>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</div>
</div
最後需要一個js完成這完成檔來,檔名要和action一樣
# add_review.js.erb
$("#modal-window").html("<%= escape_javascript(render partial: 'new_review') %>");