#<Post::ActiveRecord_Relation:0x58ce72> 的未定义方法“评论”

undefined method `comments' for #<Post::ActiveRecord_Relation:0x58ce72>

我不断收到 'Comments' 的未定义方法,它看起来一切正常,但运气不佳是涉及的代码

型号

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

-----Post 涉及控制器--------

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>

在您的 index 操作中,您将 @post 实例化为 ActiveRecord_Relation,此处:

def index
  @post = Post.all
end

并且,您尝试在 @post(一个 ActiveRecord_Relation)上调用 comments,此处:

<div class="comment-form">
  <%= form_for([@post, @post.comments.build ], local:true) do |form| %>
    <%= f.text_field :content, placeholder: 'Add a comment...' %>
  <% end %>
</div>

但是,正如错误所说,ActiveRecord_Relation 没有响应 comments

顺便说一句,您不应该为 ActiveRecord_Relation 等集合使用单数变量名称 (@post)。这很混乱,会导致问题。

您必须将 accepts_nested_attributes_for 添加到您的模型中

class Post < ApplicationRecord
  validates :user_id, presence: true
  belongs_to :user
  has_many :comments, dependent: :destroy
  validates :image, presence: true
  # Here
  accepts_nested_attributes_for :comments
  has_attached_file :image, styles: { :medium => "640x" }
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

end

我找到了必须删除 "View" 格式上的“@”的解决方案,为什么?我不知道,但它现在可以正常工作了,它通过了代码,没有错误

<div class="comment-form">
<%= form_for([post, post.comments.build ], local:true) do |form| %>
<%= form.text_field :content, placeholder: 'Add a comment...' %>
<% end %>

它可以在没有

的情况下工作
accepts_nested_attributes_for :comments

我放这个是为了让其他人可能比我更容易解决问题