【发布时间】:2018-03-08 21:08:09
【问题描述】:
我不断收到未定义的“评论”方法,看起来一切都很好,但这里没有运气是所涉及的代码
型号
class Post < ApplicationRecord
validates :user_id, presence: true
belongs_to :user
has_many :comments, dependent: :destroy
validates :image, presence: true
has_attached_file :image, styles: { :medium => "640x" }
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
class Comment < ApplicationRecord
belongs_to :post
belongs_to :user
end
控制器
---Comments Controller----
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_params)
@comment.user_id = current_user.id
if @comment.save
create_notification @post, @comment
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
else
flash[:alert] = 'Check the comment form, something went wrong.'
render root_path
end
end
-----涉及后控制器--------
def index
@post = Post.all
end
查看
<div class="comment-form">
<%= form_for([@post, @post.comments.build ], local:true) do |form| %>
<%= f.text_field :content, placeholder: 'Add a comment...' %>
<% end %>
</div>
错误
NoMethodError in Posts#index
Showing C:/Sites/Womberry2/app/views/posts/index.html.erb where line #56 raised:
undefined method `comments' for #<Post::ActiveRecord_Relation:0x58ce720>
Extracted source (around line #56):
<div class="comment-form">
<%= form_for([@post, @post.comments.build ], local:true) do |form| %>
<%= f.text_field :content, placeholder: 'Add a comment...' %>
<% end %>
</div>
【问题讨论】:
-
能否格式化您的代码
-
请注意日志中的错误
-
jvillian 只是帮助我做到这一点谢谢我也是在 Stack Over Flow 上发布问题的新手
-
你并没有真正说出你想要做什么。因此,很难知道如何提供帮助。看起来您正试图在帖子索引页面上显示所有帖子,每个帖子都有一个 cmets 表单。你之前发过这个问题吗?似曾相识。
-
我没有这是我的第一篇文章...我试图将一篇文章与 cmets 连接我正在关注该应用程序的教程我还检查了 ruby 指南,并且有一个示例可以将文章附加到评论和我的基本结构相同,但我不知道是什么错误
标签: ruby-on-rails comments instagram