jeudi 1 janvier 2015

Rails ajax first request not showing up unless I refresh the page


I have a view that has a form to create a new post using Ajax, and it also renders all the posts and adds the newly added post to them. The problem is when I post the very first post, the page does not show it unless I refresh, then if I refresh it shows up and when I add more posts Ajax works fine.


Here is the view index.html.erb :



<%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
<%= link_to 'Edit my account', edit_user_registration_path %>
<%= form_tag search_posts_path, method: :get do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", name: nil %>
<% end %>

<b> Study requests </b>

<%= form_for(@post, remote: true) do |f| %>

<%=f.label :Course_name %>
<%=f.select :course_name, options_for_select(course_names) %><br/>

<%=f.label :Course_number %>
<%=f.select :course_number, options_for_select(course_numbers) %> <br/>

<%=f.submit %>
<% end %>
<%= render @posts %>


The partial is _post.html.erb :



div id="post">
<%= post.user_name%>
</div>


Controller :



def index
@posts = Post.all.order('id DESC')
@post = Post.new
end

def create
@post = current_user.posts.build(post_params)

@post.save
respond_to do |format|
format.html { redirect_to @post, notice: "Study request successfully added" }
format.js {}
format.json { render json: @post, status: :created, location: @post }
end
end


And finally my create.js.erb :



$("<%= escape_javascript(render @post) %>").prependTo("#post");




Aucun commentaire:

Enregistrer un commentaire