【问题标题】:Ruby on Rails error: undefined method `comments_path'Ruby on Rails 错误:未定义的方法“comments_path”
【发布时间】:2014-12-17 20:45:33
【问题描述】:

我正在创建一个用户可以在其中评论帖子的应用。但是,我在尝试显示帖子时遇到错误:ArgumentError in PostsController#show First argument in form cannot contain nil or be empty

在我尝试render 'shared/comment_form'的那一行失败了

这是我的posts/show.html.erb

<% provide(:title, @post.title) %>
  <div class="post-details">
    <div class="post-title">@post.title</div>
    <div class="post-url">@post.url</div>
    <div class="post-content">@post.content</div>
    <%= render 'shared/comment_form' if logged_in? %>
    <% if @post.comments.any?  %>
      <h3>Comments</h3>
      <ol class="comments">
        <%= render @comments  %>
      </ol>
    <% end  %>
  </div>

还有我的posts_controller.rb

类 PostsController

 def create
   @post = current_user.posts.build(post_params)
   if @post.save
     flash[:success] = "Post created!"
     redirect_to root_url
   else
     @feed_items = []
     render 'static_pages/home'
   end
 end

 def show
   @post = Post.find(params[:id])
 end

 private

   def post_params
     params.require(:post).permit(:title, :url)
   end
end

这是我的 shared/_comment_form.html.erb 部分:

<%= form_for(Comment.new) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
   <div class="field">
      <%= f.text_area :content, placeholder: "Compose new comment..." %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

还有我的cmets_controller.rb

class CommentsController < ApplicationController

  before_action :logged_in_user, only: [:create, :destroy]

def create
  @comment = current_user.comments.build(comment_params)
  if @comment.save
    flash[:success] = "Comment created!"
    redirect_to request.referrer || root_url
  else
    render 'new'
  end
end

def new
  @comment = Comment.new
end

def destroy
  @comment.destroy
  flash[:success] = "Comment deleted"
  redirect_to request.referrer || root_url
end

private

  def comment_params
    params.require(:comment).permit(:content)
  end
end

顺便说一句:我知道在我的 form_for 中使用 Comment.new 是不习惯的——我也有这个问题,但我想一次解决一个问题(除非他们以某种方式参与)

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我怀疑您的 config/routes.rb 文件中没有用于 cmets 的条目,即:

    resources :comments
    

    【讨论】:

    • 这是真的——而且是一个重要的疏忽!但是,我现在收到错误“'nil' 不是 ActiveModel 兼容的对象。它必须实现:to_partial_path”
    • 好吧...我想现在的问题是这条线&lt;%= render @comments %&gt;应该是&lt;%= render @post.comments %&gt;
    • 你是对的 - 我必须通过@post访问comments
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2022-11-19
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多