I'm trying to use jQuery to create posts with a form in my Rails 3 project. Here's what I have:
look below for updated results
create.js.erb:
$("#posts").prepend("#{render(:partial => 'posts')}");
layouts/application.html.erb:
...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<%= javascript_include_tag 'rails' %>
<%= csrf_meta_tag %>
...
posts_controller.rb:
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
# ...
format.js
else
# ...
end
end
end
When I submit the post form it puts text like #{render(:partial => 'posts')}
where the post ajax should be.
EDIT:
by changing create.js.erb
to:
$("#posts").prepend("<%= render(:partial => 'posts')%>");
I get this error in the terminal when I submit the form:
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: <%- for post in @posts -%>
2: <div class="post">
3: <%= link_to post.title, post %>
4: <%- if post.name? -%>
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)