简体   繁体   中英

Rails: Routing Error, comment model to micropost model

I made a commenting system and I am trying to get it to post under a micropost but I constantly get this routing error. Any suggestions? All help is much appreciated!

Routing Error

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

Form

<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>

comment controller

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

routes

resources :microposts do
  resources :comments
end

Micropost Model

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

User Controller

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

The reason you are getting the error is that you are trying to build a form for a comments of a micropost that does not exist yet in the database.

the form, there is a -

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

And in UsersController you have -

  @micropost = Micropost.new

comment is a sub-resource of micropost, so a url that creates a comment should look like /micropost/:id/comments where :id is the id of micropost. That is possible only after the micropost is saved.

So I believe your action should assign @micropost to an existing post, or create one right there to have the form working. Something like -

   @micropost = Micropost.last || Micropost.create

would at least get rid of the error.

I'll try this again (deleted my other answer since, as Marc Talbot pointed out, was not the correct response to your issue) .

Perhaps the issue is as simple as making :microposts be :micropost instead (to reflect your model's name) .

resources :micropost do
  resources :comments
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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