我正在尝试使用jQuery在我的Rails 3项目中创建带有表单的帖子。这就是我所拥有的:
查看以下更新结果
create.js.erb:
$("#posts").prepend("#{render(:partial => 'posts')}");
布局/ 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
当我提交帖子表单时,它会将#{render(:partial => 'posts')}
这样的文字放在ajax应该是的位置。
编辑:
将create.js.erb
更改为:
$("#posts").prepend("<%= render(:partial => 'posts')%>");
我在提交表单时在终端中收到此错误:
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)
答案 0 :(得分:2)
你错过了erb标签:
$("#posts").prepend("<%=render(:partial => 'posts')%>");
您似乎正在尝试再次呈现完整的帖子,我认为您确实想要呈现一个帖子。这将导致出现重复的帖子。在您的create方法中没有设置@posts变量,导致出现nil错误。您应该创建另一个名为_post的部分并在其中呈现单个帖子。请注意,create方法设置@post,但不设置@posts。这就是你的错误来自哪里,因为@posts是零。这个错误有点误导你正在使用的b / c:
for post in @posts
我建议使用在Ruby中更广泛使用的以下语法(与“for”具有相同的效果):
@posts.each do |post|
我认为这个railscast可能会对你有所帮助。根据你在这里展示的内容,我认为Ryan几乎完全一样,但是使用轮询方法而不是提交表单。特别注意他创建_comment.html.erb的部分以呈现单个注释。