Rails发表评论嵌套在类别中

时间:2013-09-10 08:12:02

标签: ruby-on-rails ruby-on-rails-3

我有一个rails博客,其中所有帖子都嵌套在类别下,现在我添加的评论嵌套在帖子下但表单却抛出undefined method `post_comments_path'错误。

我想我需要让@posts像@ categories.post一样,但我不确定。

路线

resources :categories do
  resources :posts, path: 'article' do
    resources :comments, :only => [:create]
  end
end

控制器

def create
    @post = Post.find(params[:post_id])
    @comment = @posts.comments.create!(params[:comment])
    redirect_to @post
end

视图

<%= simple_form_for [@post, Comment.new ], :remote => true do |f| %>
  <%= f.input :name %>
  <%= f.input :email %>
  <%= f.input :comment %>
  <%= f.button :submit %>
<% end %>

1 个答案:

答案 0 :(得分:1)

我认为你忘记了类别。您需要提供一个类别:

控制器

def new
  ...
  @category = Category.find(params[:category_id])
  ...
end

def create
    @post = Post.find(params[:post_id])
    @comment = @posts.comments.create!(params[:comment])
    redirect_to @post
end

视图

<%= simple_form_for [@category, @post, Comment.new ], :url => category_post_comments_path, :remote => true do |f| %>
  <%= f.input :name %>
  <%= f.input :email %>
  <%= f.input :comment %>
  <%= f.button :submit %>
<% end %>

或从路线中删除类别:

路线

resources :posts, path: 'article' do
  resources :comments, :only => [:create]
end