2014-02-25 16 views
0

看看這個問題,我剛纔問:Comments on multiple models多態評論路線錯誤

到目前爲止,我所擁有的一切設置正確,我的意見表,我的模型和控制器。

但是,我遇到了一些路由錯誤。

在我的路線文件:

resources :posts do 
    resources :comments do 
    member do 
     put "like", to: "comments#upvote" 
    end 
    end 

    end 

    resources :books do 
    resources :comments do 
    member do 
     put "like", to: "comments#upvote" 
    end 
    end 

    end 

我的評論形式:

<% form_for [@commentable, Comment.new] do |f| %> 
    <p> 
    <%= f.text_area :body %> 
    </p> 
    <p><%= f.submit "Submit" %></p> 
<% end %> 

這是我得到的錯誤:

未定義的方法`comments_path」

任何想法如何讓路線工作?

編輯:

這是我在我的意見控制器:

def index 
    @commentable = find_commentable 
    @comments = @commentable.comments 
end 

def create 
    @commentable = find_commentable 
    @comment = @commentable.comments.build(params[:comment]) 
    if @comment.save 
    flash[:notice] = "Successfully created comment." 
    redirect_to :id => nil 
    else 
    render :action => 'new' 
    end 
end 

private 

def find_commentable 
    params.each do |name, value| 
    if name =~ /(.+)_id$/ 
     return $1.classify.constantize.find(value) 
    end 
    end 
    nil 
end 
+1

什麼是'@ commentable'變量? –

+0

剛剛添加了一個編輯問題,顯示我在控制器中的內容 –

+0

您確定在任何控制器操作正在呈現初始評論表單時定義了「@ commentable」嗎? –

回答

2

@Katie,@commentable應該針對您要呈現評論表單的每個操作加載。我認爲你放棄comments#new贊成使用books#showposts#show來渲染表單(這很好),但每次你想渲染表單時都需要加載該變量。

然而,由於books#show定義一個變量@commentable是不是很傳神(你可能已經有了一個@book定義),這裏是我建議:

創建一個新的部分(如果你沒有一個已經)):

<% form_for [commentable, Comment.new] do |f| %> 
    <p> 
    <%= f.text_area :body %> 
    </p> 
    <p><%= f.submit "Submit" %></p> 
<% end %> 

注意commentable在這裏不是一個實例變量。在渲染局部變量時,您將其定義爲局部變量。某處在books/show.html.erb

<%= render partial: "comments/form", locals: { commentable: @book } %> 

顯然,在其它視圖,更換@book與任何變量應該是commentable

現在您將遇到另一個問題,即表單數據不會帶有commentable_typecommentable_id屬性。有很多方法可以讓你進入你的CommentsController;這裏有一個簡單的使用隱藏字段:

<% form_for [commentable, Comment.new] do |f| %> 
    <%= hidden_field_tag :commentable_type, commentable.class.to_s %> 
    <%= hidden_field_tag :commentable_id, commentable.id %> 
    <p> 
    <%= f.text_area :body %> 
    </p> 
    <p><%= f.submit "Submit" %></p> 
<% end %> 

你需要改變find_commentable行動,一些更簡單:

def find_commentable 
    params[:commentable_type].constantize.find(params[:commentable_id]) 
end 
+0

謝謝soooo多!我一定在做錯事,我沒有在我的書籍展示視圖中看到錯誤,但表單根本不是渲染,如果有時間,我們可以在聊天框中繼續嗎? –

+1

當然:[http://chat.stackoverflow.com/rooms/info/48418/question22027185](http://chat.stackoverflow.com/rooms/info/48418/question22027185?tab=general) –

1

如果您在PostsController#show作用下呈現評論表單,那麼你要確保@commentable是內定義那個動作在某處。

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

這樣一來,在form_for [@commentable, Comment.new]呼叫使用@commentable定義。