我继续为'评论'获取未定义的方法它看起来一切都很好但是这里的代码没有运气
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>
答案 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 {
// ...
}
我这样做,所以其他人可能比我更容易解决问题