Rails:如何仅使用.collection获取已保存的模型?

jum*_*oel 6 activerecord ruby-on-rails

我有has_many模型评论的模型Post .

在一个Posts show动作上,有一个Comments找到的列表@comments = @post.comments.

我还有一个创建新的表单Comments.表单的对象是使用@comment = @post.comments.build.

这一切都适用于列表和成功创建评论.

提交评论时出现错误时会出现此问题.错误以相同的形式显示(因此,打开Post#show)via render "posts/show".在这种情况下,我必须@comments = @post.comments再次设置,但这次评论列表包括用户尝试创建的尚未保存的评论.

我通过使用解决了它@post.comments.all,它只给了我保存的模型,但Rails抱怨这在Rails 4中已被弃用.

如何从我收到的评论列表中删除未保存的评论@post.comments

Mat*_*att 1

您可以向注释模型添加范围以仅查找数据库行而不是内存数据,例如:

class Comment < ActiveRecord::Base
  scope :by_post, ->(post) { where(post: post) }
end
Run Code Online (Sandbox Code Playgroud)

调用者:@comments = Comment.by_post(@post)