我使用ajax渲染呈現表單的部分(我不能直接渲染表單)。當我在沒有Ajax的情況下渲染表單時,發佈評論的效果很好,但是使用Ajax時,似乎部分無法訪問@post變量。使用ajax渲染兩個部分表單
<%= link_to "Render form", submit_comment_path, :remote => true %>
<div id="form">
</div>
我有一個submit_comment.js文件看起來像這樣:
$("#form").html("<%= j render(partial: 'comment_partial', locals: {post: @post}) %>");
的comment_partial觀點:
<%= render 'comments/form' %>
表單視圖:
<%= simple_form_for [post, Comment.new] %>
...
的submit_comment_path路線:
get '/submit_comment', to: 'posts#submit_comment', as: :submit_comment
的帖子控制器(它被呈現在顯示頁面上):
def show
@post = Post.find(params[:id])
end
def submit_comment
respond_to do |format|
format.html
format.js
end
end
和評論控制器:
def create
@post = Post.find(params[:post_id])
end
如果我試圖發表新評論它給了我一個路由錯誤,並帶我到/posts//comment
。將post.id
置於comment_partial中會給我一個未定義的錯誤。
謝謝你解釋得那麼好,非常感謝:) – user2759575
你打賭!很高興我能幫忙! –