Rails - AJAX/JQuery not working -
for application, have projects users can make comment (class newcomments) postings. right posts great on page refresh. trying use ajax/jquery post no page refresh. following railscasts tutorial.
so right now, posts made database , page not refresh. when refresh, posts shows up. page render comments specific project on projects/_comments.html.erb.
question: how adjust new comment made renders?
newcomments_controller.rb
def create @newcomment = @commentable.newcomments.new(params[:newcomment]) if @newcomment.save respond_to |format| format.html { redirect_to comments_project_path(@commentable) } format.js end else render :new end end
view/newcomments/_form.html.erb
<span class="comment"> <%= form_for [@commentable, @newcomment], remote: true |f| %> <%= f.text_area :content, rows: 3, :class => "span8" %> <%= f.hidden_field :user_id, :value => current_user.id %> <%= f.submit "add comment", :class => "btn btn-header" %> <% end %> </span>
view/newcomments/create.js.erb
$('#newcomment').append('<%= j render(@newcomments) %>');
projects_controller.rb
def comments @commentable = @project @newcomments = @commentable.newcomments.newest.page(params[:comments_page]).per_page(10) @newcomment = newcomment.new respond_to |format| format.html # show.html.erb format.json { render json: @project.comments } end end
projects/comments.html.erb
<%= render 'comments' %>
projects/_comments.html.erb
<%= render @newcomments %>
view/newcomments/_newcomment.html.erb
<div class="comments"> <%= link_to newcomment.user.name %></strong> posted <%= time_ago_in_words(newcomment.created_at) %> ago <%= newcomment.content %> </div> <span class="comment"> <%= form_for [@commentable, @newcomment] |f| %> <div class="field"> <%= f.text_area :content, rows: 3, :class => "span8" %> </div> <%= f.hidden_field :user_id, :value => current_user.id %> <div class="actions"> <%= f.submit "add comment", :class => "btn btn-header" %> </div> <% end %> <% unless newcomment.newcomments.empty? %> <%= render @newcomments %> <% end %> </span>
try binding ajax actions described here: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
also, consider returning render comments partial html instead of json comment object, need tell in form after :remote directive :'data-type'=>'html', returned html hit function binded on ajax success, , swap html of container div with, example, jquery
Comments
Post a Comment