jquery - Ajax submit form, rails3 -
update, going off frank wrote below:
in post's show view have:
<span id="commentspartial"> <%= render 'comments' %> </span> in comments partial have:
<% @comments.each |comment| %> <%= comment.description %> <% end %> <br/> <%= render '/comments/form' %> in form partial have:
<%= form_for [@comment], :remote => true |f| %> <% if @comment.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@comment.errors.count, "error") %> prohibited comment being saved:</h2> <ul> <% @comment.errors.full_messages.each |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.text_area :description, :class => "forms", :style => "width:80%;height:120px;"%> </div> <div class="actions" style="margin-top:10px;"> <%= f.hidden_field :user_id, :value => current_user.id %> <%= f.hidden_field :post_id, :value => @post.id %> <%= f.submit :class => "button-style" %> </div> <% end %> my views/comments/create.js.erb page has:
$("#commentspartial").html("<%= escape_javascript(render('comments')) %>"); when submit new comment - created. page remains static. when watch in firebug, see comment created, , there called on post returns success - though page doesn't update... confused
i think following wrong approach , think jquery instead of "rails way" it. can pass option :remote => :true form_tag or form_for in order tell rails use ajax instead.
probably want nest comment model, (google: nested routes), , have file in
app/views/comments/create.js.erb whcih this:
$("#comments").prepend("<%= escape_javascript render(@comment) %>"); $('#comments_count').html('<%= pluralize(@comment.image.comments.count, "comment") %>'); $("#comment_body").val(""); $("#comments .comment_body:first").effect("highlight", { color:"#d3ecf4"}, 3000); here specify should done update view on success.
in controller can use:
def create @comment = comment.create!(params[:comment]) end and view like:
<div id="comments"> <%= render @comments %> </div> <% form_for [@image, comment.new], :remote => true |f| %> <%= render 'comment_fields', :f => f %> <% end %> supposed want comment on image.
my _comment_fields.html.erb partial looks this:
<p id="new_comment" class="add_comment"> <%= f.hidden_field :user_id, :value => current_user.id %> <%= f.hidden_field :image_id, :value => @image.id %> <%= f.label :body, "leave comment" %><br /> <%= f.text_area :body, :rows => 5, :cols => 25 %> </p> <p> <%= f.submit "add comment" %> </p> this rails' way handle javascript unobstrusively. ressource on this screencast.
Comments
Post a Comment