【问题标题】:Rails Post comments nested within categoryRails 发表评论嵌套在类别中
【发布时间】:2013-09-10 08:12:01
【问题描述】:

我有一个 Rails 博客,其中所有帖子都嵌套在类别下,现在我添加了嵌套在帖子下的 cmets,但表单抛出 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 %>

【问题讨论】:

  • 尝试运行rake routes。你会看到最可能的路径是:new_category_post_comment_path

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


【解决方案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

【讨论】:

  • 我认为这是问题所在,但我仍然遇到同样的错误。有什么想法吗?
  • 现在我收到此错误 No route matches {:controller=>"cmets"} 我不明白。
  • params[:category_id]) 和 params[:post_id] 设置了吗?看起来他们返回 nil。
  • 是的,我相信他们已经确定了。当我在更好的错误控制台中键入@post.category.id 时返回一个 id。
  • @category 本身怎么样?
猜你喜欢
  • 2021-09-09
  • 1970-01-01
  • 2012-09-17
  • 1970-01-01
  • 2014-08-28
  • 1970-01-01
  • 2015-03-28
  • 1970-01-01
  • 2015-09-01
相关资源
最近更新 更多