#loc :: activerecord_relation:0x58ce72>的未定义方法`comments'

时间:2018-03-08 21:08:10

标签: ruby-on-rails comments instagram

我继续为'评论'获取未定义的方法它看起来一切都很好但是这里的代码没有运气

模型

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>

3 个答案:

答案 0 :(得分:0)

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

def index
  @post = Post.all
end

并且,您尝试在comments@post)上致电ActiveRecord_Relation,此处:

<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做出回应。

顺便说一句,你不应该使用单数变量名(@post)作为ActiveRecord_Relation之类的集合。这令人困惑,并会引发问题。

答案 1 :(得分:0)

您必须将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

答案 2 :(得分:0)

我找到了解决方案,我必须删除&#34; @&#34;在&#34; View&#34;格式为什么??我不知道,但它现在可以正常传递代码

for myIP in tableView.indexPathsForVisibleRows ?? [] {
    if let cell = tableView.cellForRow(at: myIP) {
        // ...
    }
}

它可以在没有

的情况下工作
for cell in tableView.visibleCells {
    // ...
}

我这样做,所以其他人可能比我更容易解决问题