2015-06-09 40 views
0

我使用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中會給我一個未定義的錯誤。

回答

1

這個難題的主要內容是理解實例變量(本例中是@post)只要Controller呈現任何東西就會消失。

您正確地分配@post當渲染顯示頁面:

def show 
    @post = Post.find(params[:id])  
end 

然而,@post消失第二是show.html.erb完成渲染。當你點擊鏈接到點擊提交評論方法,是越來越不創建@post ...

def submit_comment 
# No instance variables here! :(
respond_to do |format| 
    format.html 
    format.js 
end 
end 

這意味着,submit_comment.js文件不知道哪些帖子後產生的一種形式。

但是,它並不像將另一個Post.find(params [:id])引入submit_comment方法那麼簡單。您需要:

  1. 定義依賴帖子ID路線
  2. 變化show.html.erb鏈接到包含特定@ post.id
  3. 然後找到相應的職位爲...創建評論。

它可能是這個樣子......

路線。RB

... 
resources :posts do 
    member do 
    get 'submit_comment' 
    end 
end 
... 

閱讀上成員的路線at the Rails Guide。還有其他方式可以完成類似的路線。

帖子/ show.html.erb

<%= link_to "Render form", submit_comment_post_url(@post), :remote => true %> 

注意,Rails的默認網址助手是不是你已經有了,如果你使用成員路線的不同。

posts_controller.rb

def submit_comment 
    @post = Post.find(params[:id]) 
    ... 
end 

希望幫助!快樂的形式!

+0

謝謝你解釋得那麼好,非常感謝:) – user2759575

+0

你打賭!很高興我能幫忙! –