我正嘗試使用jQuery在我的Rails 3項目中創建一個表單。下面是我有:下面爲什麼不使用UJS/jQuery進行局部渲染?
查找更新的結果
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)
我得到一個ActionView :: Template :: Error與此。我在我的問題中發佈了輸出。 – BasicObject 2010-09-09 19:44:32
我的答案已更新。請參閱上文。 – johnmcaliley 2010-09-10 11:36:41