2016-10-28 32 views
0

導軌5的應用程式導軌5:@ post.comments是空的,但<%如果@ post.comments%>不執行else塊,而是充當如果真

我具有問題,即一個視圖中我有一組簡單的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?返回false。和@post.comments返回:

Comment Load (1.3ms) SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = $1 AND "comments"."commentable_type" = $2 [["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 

回答

1

因爲在Ruby只是falsenil是falsey值。我的意思是,這些值在布爾上下文中是錯誤的。在你的代碼中,大概@post.comments[][]是在Ruby中的true

+0

啊,我應該想到這一點。我不知道爲什麼我沒有,這不是我第一次與Rails合作。我責怪工作日的結束。 '@ post.comments.any?'是解決方案。 – Antonio

+0

是的,這是解決方案:) – Ursus

1

它是因爲@post.comments沒有記錄,而空數組是ruby中的真實對象。只有無和假都是錯誤的。

你應該改變你的代碼問if @post.comments.present?

相關問題