Ruby on Railsでアプリケーションを開発しています。
現在、投稿に対してBootstrapのモーダルでコメントを付けられるような機能を追加しようとしているのですが、上手くモデルの情報が取得出来ずにハマっています。
やりたいこと
薄くて見えづらいですが、以下の画像中の鉛筆マークを押すと、モーダルが現れ、その投稿に対してコメントが出来るようにしたいです。
現状
ですが、下の画像は右側の商品の鉛筆をクリックして出てきたモーダルです。ご覧の通り左側の情報を取得してしまっています。
コードは以下のとおりです。
_post.html.erb
Ruby
1<% if @posts %> 2 <% if @post %> 3 <ul class="posts ul-sortable"> 4 <% end %> 5 <% @posts.each do |post| %> 6 <li class="post" data-url="<%= sort_post_path(post.id) %>"> 7 <%= link_to (image_tag(post.product.image_url, style: "width: 180px;height: 250px;")), post.product.url, class: "post-image"%> 8 <div class="post_title"> 9 <%= link_to post.product.title.truncate(30), post.product.url %> 10 </div> 11 <div class="post_comments"> 12 <% if post.content %> 13 <%= post.content %> 14 <% end %> 15 </div> 16 <ul class="edit_post"> 17 <% if current_user && current_user.id == post.user.id %> 18 <li class="item"> 19 <%= link_to post_path(post.id), method: :put, :data => {:toggle=>"modal", :target => "#exampleModalCentered"}, :id => "add_coment", remote: true do %> 20 <i class="fa fa-pencil"></i> 21 <% end %> 22 </li> 23 <li class="item"> 24 <%= link_to post_path(post.id), method: :delete, "data-confirm" => "投稿を消去しますか?", :class => "trash" do %> 25 <i class="fa fa-trash-o trash"></i> 26 <% end %> 27 </li> 28 <% end %> 29 </ul> 30 31 <% if post && current_user %> 32 <div class="modal" id="exampleModalCentered" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenteredLabel" aria-hidden="true"> 33 <div class="modal-dialog modal-dialog-centered" role="document"> 34 <div class="modal-content"> 35 <div class="modal-header"> 36 <h5 class="modal-title" id="exampleModalCenteredLabel"><%= post.product.title %></h5> 37 <!--button type="button" class="close" data-dismiss="modal" aria-label="Close"> 38 <span aria-hidden="true">×</span> 39 </button--> 40 </div> 41 <div class="modal-body text-center"> 42 <%= form_for post, html: { class: 'form js-form' } do |f|%> 43 <%= f.text_area :content, class: 'form__text-field js-form__text-field' %> 44 </div> 45 <div class="modal-footer"> 46 <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> 47 <%= f.submit class: 'form__submit js-submit btn btn-primary' %> 48 <% end %> 49 </div> 50 </div> 51 </div> 52 </div> 53 <% end %> 54 <% end %> 55 </li><!--post--> 56<% end %>
post.js.erb
JavaScript
1$(function() { 2 $('#add_comment').on('submit', function(e) { 3 e.preventDefault(); 4 var textField = $(post.content); 5 var content = textField.val(); 6 7 $.ajax({ 8 type: 'POST', 9 url: '/posts.json', 10 data: { 11 post: { 12 content: content 13 } 14 }, 15 dataType: 'json' 16 }) 17 }); 18})
posts_controller.rbの該当箇所
Ruby
1def update 2 @post = Post.find(params[:id]) 3 if @post.update(comment_params) 4 respond_to do |format| 5 format.html { redirect_to user_path(@post.user) } 6 format.json { render json: @post } 7 end 8 else 9 render :index 10 end 11 end
他にも必要な情報有りましたら載せます。
よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。