2013-02-05 222 views
2

所以我正在製作一個使用ROR的網絡應用程序,我無法弄清楚這個表單的正確語法是什麼。我目前正在爲註釋和帖子製作關聯類型的代碼。Ruby on Rails協會表格

<%= form_for @comment do |f| %> 
<p> 
<%= f.hidden_field :user_id, :value => current_user.id %> 
<%= f.label :comment %><br /> 
<%= f.text_area :comment %> 
</p> 

<p> 
<%= f.submit "Add Comment" %> 
</p> 
<% end %> 
+0

有什麼問題嗎? –

+1

通常,您不必在表單中傳遞'user_id'。在「控制器」中關聯。 –

+0

感謝您的答案球員,但我仍然得到這個錯誤: 未定義的方法'post_comments_path'爲#<#:0x3f805e0> – Pau

回答

4

您的形式是很好,除了第一行(你不需要隱藏字段爲USER_ID,這就是通過你的關係做了):

<%= form_for(@comment) do |f| %> 

應該是:

<%= form_for([@post, @comment]) do |f| %> 

現在您呈現一個表單,用於創建或更新特定帖子的評論。

但是,你應該改變你的模型和控制器。

class Post 
    has_many :comments 
end 

class Comment 
    belongs_to :post 
end 

這會讓您訪問@ post.comments,顯示屬於特定帖子的所有評論。

在你的控制器,你可以爲特定的訪問後評論:

class CommentsController < ApplicationController 
    def index 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.all 
    end 
end 

這種方式,您可以訪問的評論索引所需的特定訊息。

更新

一件事,你的路線也應該是這樣的:

AppName::Application.routes.draw do 
    resources :posts do 
    resources :comments 
    end 
end 

這會給你訪問post_comments_path(和較多的路由)

+0

謝謝。 :) 忘記編輯我的路線。 -.- – Pau