導軌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
啊,我應該想到這一點。我不知道爲什麼我沒有,這不是我第一次與Rails合作。我責怪工作日的結束。 '@ post.comments.any?'是解決方案。 – Antonio
是的,這是解決方案:) – Ursus