Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't this partial render with UJS / jQuery?
    primarykey
    data
    text
    <p>I'm trying to use jQuery to create posts with a form in my Rails 3 project. Here's what I have:</p> <p><em>look below for updated results</em></p> <p>create.js.erb:</p> <pre><code>$("#posts").prepend("#{render(:partial =&gt; 'posts')}"); </code></pre> <p>layouts/application.html.erb:</p> <pre><code>... &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt; &lt;%= javascript_include_tag 'rails' %&gt; &lt;%= csrf_meta_tag %&gt; ... </code></pre> <p>posts_controller.rb:</p> <pre><code>def create @post = Post.new(params[:post]) respond_to do |format| if @post.save # ... format.js else # ... end end end </code></pre> <p>When I submit the post form it puts text like <code>#{render(:partial =&gt; 'posts')}</code> where the post ajax should be.</p> <p>EDIT: by changing <code>create.js.erb</code> to:</p> <pre><code>$("#posts").prepend("&lt;%= render(:partial =&gt; 'posts')%&gt;"); </code></pre> <p>I get this error in the terminal when I submit the form:</p> <pre><code>Rendered posts/_posts.html.erb (13.6ms) Rendered posts/create.js.erb (80.4ms) Completed in 1631ms ActionView::Template::Error (You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each): 1: &lt;%- for post in @posts -%&gt; 2: &lt;div class="post"&gt; 3: &lt;%= link_to post.title, post %&gt; 4: &lt;%- if post.name? -%&gt; app/views/posts/_posts.html.erb:1:in `_app_views_posts__posts_html_erb___692646030_16112196__738457576' app/views/posts/create.js.erb:1:in `_app_views_posts_create_js_erb__431255654_16166988__591965598' app/controllers/posts_controller.rb:39:in `create' Rendered /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (10.6ms) Rendered /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (54.3ms) Rendered /usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.0.0/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (102.1ms) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload