Ruby on Rails Association Form
所以我正在使用ROR创建一个Web应用程序,我无法弄清楚这个表单的正确语法是什么。 我目前正在为评论和post制作一种关联类型的代码。
current_user.id %>
您的表单很好,除了第一行(并且您不需要user_id的隐藏字段,这是通过您的关系完成的):
<%= form_for(@comment) do |f| %>
应该:
<%= form_for([@post, @comment]) do |f| %>
现在,您渲染一个表单,用于创建或更新特定post的评论。
但是,您应该更改模型和控制器。
class Post has_many :comments end class Comment belongs_to :post end
这样您就可以访问@ post.comments,显示属于特定post的所有评论。
在您的控制器中,您可以访问特定post的评论:
class CommentsController < ApplicationController def index @post = Post.find(params[:post_id]) @comment = @post.comments.all end end
这样,您就可以访问特定post的评论索引。
更新
还有一件事,你的路线也应该是这样的:
AppName::Application.routes.draw do resources :posts do resources :comments end end
这将使您可以访问post_comments_path(以及更多路由)