Hi I'm fairly new to rails and am trying to implement AJAX in my Rails application.
The problem is that when I submit my form it seems like the create action is definitely called, as when I refresh the page the new element appears, but the table doesn't automatically refresh.
topics/show.html.erb relevant code:
<div class="row" id="toberefreshed">
<%= render('show_partial', :locals => {:topic => @topic}) %>
</div>
topics/_show_partial.html.erb relevant code:
<table class = "opinionlist" align="center">
<% opinions = @topic.opinions %>
<% cons = opinions.select{|opinion| opinion.type_of == 'con'} %>
<% pros = opinions.select{|opinion| opinion.type_of == 'pro'} %>
<tr>
<% pros.each do |pro|%>
<td>
<div class="article-body">
<%= pro.content %>
</div>
<div class="article-meta-details">
<small>
Created by: <%= pro.user.username %>
<%= time_ago_in_words(pro.created_at) %> ago,
</small>
</div>
</td>
<% end %>
<% if pros.length < cons.length %>
<% difference = cons.length - pros.length%>
<% difference.times do %>
<%= content_tag(:td) %>
<% end %>
<% end %>
<td><%= render 'opinions/form', opinion: Opinion.new, typeOf: "pro", :topic => @topic %></td>
</tr>
<tr>
<% cons.each do |con|%>
<td>
<div class="article-body">
<%= con.content %>
</div>
<div class="article-meta-details">
<small>
Created by: <%= con.user.username %>
<%= time_ago_in_words(con.created_at) %> ago,
</small>
</div>
</td>
<% end %>
<% if pros.length > cons.length %>
<% difference = pros.length - cons.length %>
<% puts "DIFFERENCE: " + difference.to_s %>
<% difference.times do %>
<%= content_tag(:td) %>
<% end %>
<% end %>
<td>
<%= render 'opinions/form', opinion: Opinion.new, typeOf: "con", :topic => @topic %>
</td>
</tr>
</table>
topics/updated_view.js.erb:
$("toberefreshed").html("<%= escape_javascript(render("topics/show_partial", :locals => {:topic => @opinion.topic})) %>");
opinions_controller.rb
class OpinionsController < ApplicationController
def create
@opinion = Opinion.new(opinion_params)
@opinion.user = current_user
@opinion.topic = Topic.find(params[:to_find_id])
@opinion.type_of = params[:type_of]
if @opinion.save
flash[:success] = 'Opinion Added'
else
puts @opinion.errors.full_messages
flash[:danger] = 'Opinion not Added'
end
respond_to do |format|
format.js
end
end
private
def opinion_params
params.require(:opinion).permit(:content)
end
end
EDIT: opinions/_form.html.erb
<div class="row">
<div class="col-xs-12">
<%= form_for(opinion, :html=> {class:"form-horizontal", role:"form"}, remote: true) do |f| %>
<div class="form-group">
<div class="col-sm-12">
<%= f.text_area :content, rows:4, class: "form-control", placeholder: "Opinion" %>
</div>
</div>
<%= hidden_field_tag 'type_of', typeOf %>
<%= hidden_field_tag :to_find_id, @topic.id %>
<% puts "ID: " + @topic.id.to_s %>
<div class="form-group">
<div class="col-sm-12">
<%= f.submit %>
</div>
</div>
<% end %>
</div>
</div>
Thank you so much for your help, Raahil