繁体   English   中英

Rails:路由错误,注释模型到微博模型

[英]Rails: Routing Error, comment model to micropost model

我制作了一个评论系统,试图将其发布到微博下,但我不断遇到此路由错误。 有什么建议么? 非常感谢所有帮助!

Routing Error

No route matches [POST] "/microposts/comments"

形成

<div class="CommentField">
<%= form_for ([@micropost, @micropost.comments.new]) do |f| %>
<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<div class="CommentButtonContainer">
<%= f.submit "Comment", :class => "CommentButton b1" %>
</div>
<% end %>
</div>

评论控制器

class CommentsController < ApplicationController 
  def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = @micropost.comments.build(params[:comment])
    @comment.user_id = current_user.id
    @comment.save 
      respond_to do |format|
      format.html 
      format.js
    end
  end

end

路线

resources :microposts do
  resources :comments
end

微邮模型

class Micropost < ActiveRecord::Base
  attr_accessible :title, :content, :view_count
  acts_as_voteable
  belongs_to :user
  has_many :comments
  has_many :views
  accepts_nested_attributes_for :comments
end

用户控制器

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
    @school = School.find(params[:id])
    @micropost = Micropost.new
    @comment = Comment.new
    @comment = @micropost.comments.build(params[:comment])
    @microposts = @user.microposts.paginate(:per_page => 10, :page => params[:page])
  end
end

出现此错误的原因是,您正在尝试为数据库中尚不存在的micropostcomments构建表单。

表格中有-

   form_for ([@micropost, @micropost.comments.new]) do |f|

在UsersController中,您可以-

  @micropost = Micropost.new

comment是micropost的子资源,因此创建评论的url应该看起来像/micropost/:id/comments ,其中:id是micropost的ID。 只有在保存微职位后才有可能。

因此,我认为您的操作应将@micropost分配给现有帖子,或在其中创建一个以使表格正常工作。 就像是 -

   @micropost = Micropost.last || Micropost.create

至少会消除错误。

我将再次尝试(删除其他答案,因为正如Marc Talbot所指出的那样,这不是对您问题的正确答案)

也许问题就像将:micropost改为:microposts一样简单(以反映您模型的名称)

resources :micropost do
  resources :comments
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM