开发者

Why does this exist?

So how is it possible that

@article.authors.exists? 

is true, and

@article.authors.empty?

is also true????

the context is a new action:

def new
  @article = Article.new
  # @article.build.authors unless @article.authors.exists?
  # @article.build.authors if @article.authors.empt开发者_如何学Goy?
end

and

class Article < ActiveRecord::Base
  has_many :authors
  accepts_nested_attributes_for :authors
end


This is not the answer you are looking for - I misread the question. I think Jeremy had it right in his comment above.

Because in Ruby anything that is non-nil and not explicitly false evaluates to true in boolean comparisons, even 0. @article.authors, in this case, is an empty array, or []. [] is not nil, and it is not false, therefore it is evaluated as true in a boolean comparison. The empty? method on the array object returns true if the array is empty, or [], which in this case it is.

Here's some broader information about this: http://railsclub.com/2011/03/the-difference-between-nil-true-false-blank-and-empty/


Right, think I have solved it, because @article has not been saved yet,

@article.authors.exists?

runs the sql:

[1m[36mCACHE (0.0ms)[0m  [1mSELECT 1 FROM `authors` WHERE `authors `.`type` IN ('professional') AND `authors `.`article_id` IS NULL LIMIT 1[0m

So it returns whether there are any authors without an article.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜