Rails 5: @post.comments 为空,但 <% if @post.comments %> 不执行 else 块,而是像 true 一样

Rails 5: @post.comments is empty, yet <% if @post.comments %> doesn't execute the else block and instead acts as if true

Rails 5 个应用程序

我遇到一个问题,在视图中我有一组简单的 ERB 标签:

<% if @post.comments %>
  <p>Comments here</p>
<% else %>
  <p>No comments yet</p>
<% end %>

显然,如果 @post 中不存在注释,则执行底部代码块。数据库中 没有评论 ,附加到此 @post 或任何其他 post。但是,它正在执行顶部块,我看到 <p>Comments here</p> 呈现在页面上。

如果我在byebug里面查看,@post.commments.any?returnsfalse。和 @post.comments returns:

Comment Load (1.3ms)  SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" =  AND "comments"."commentable_type" =   [["commentable_id", 4], ["commentable_type", "Post"]]
#<ActiveRecord::Associations::CollectionProxy []>

这不算假的吗? <% if @post.comments %> 不应该去 else 块吗?

架构:

create_table "comments", force: :cascade do |t|
  t.text     "body"
  t.datetime "created_at",       null: false
  t.datetime "updated_at",       null: false
  t.integer  "commentable_id"
  t.string   "commentable_type"
end

create_table "forums", force: :cascade do |t|
  t.string   "name"
  t.text     "description"
  t.integer  "user_id"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
  t.index ["user_id"], name: "index_forums_on_user_id", using: :btree
end

create_table "posts", force: :cascade do |t|
  t.string   "title"
  t.text     "description"
  t.integer  "user_id"
  t.integer  "forum_id"
  t.datetime "created_at",  null: false
  t.datetime "updated_at",  null: false
  t.index ["forum_id"], name: "index_posts_on_forum_id", using: :btree
  t.index ["user_id"], name: "index_posts_on_user_id", using: :btree
end

create_table "users", force: :cascade do |t|
  t.string   "email",                  default: "", null: false
  ...
  # Devise stuff removed for brevity.
  ...
end

add_foreign_key "posts", "forums"
add_foreign_key "posts", "users"

我的模特:

#User model.
has_many :forums
has_many :posts

#Forum model.
belongs_to :user
has_many :posts

#Post model.
belongs_to :user
belongs_to :forum

#Comment model.
belongs_to :commentable, polymorphic: true
has_many :comments, as: :commentable

因为在 Ruby 中只有 falsenil 是假值。我的意思是,那些在布尔上下文中为假的值。在你的代码中 @post.comments 可能是 [][] 在 Ruby.

中是 true

因为@post.comments没有recordas,空数组是ruby中的真对象。只有 nil 和 false 是假的。

您应该更改代码以询问 if @post.comments.present?