我以为我理解 attr_* 和 map(&:name.to_proc).join(' ') 的简写符号,但我今天遇到了这个问题。
为什么设置 attr_accessor 使我无法写出类似的东西NaughtyWord.all.collect(&:word)
,而是要求我写出更长的时间NaughtyWord.all.collect{|naughty_word| naughty_word["word"]}
class NaughtyWord < ActiveRecord::Base
attr_accessor :word, :must_review
validates_presence_of :word
def self.regex_filter
words = NaughtyWord.all.collect(&:word).join("|")
end
end
#irb(main):014:0> NaughtyWord.all.collect(&:word)
# NaughtyWord Load (0.4ms) SELECT `naughty_words`.* FROM `naughty_words`
#=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
#irb(main):024:0> NaughtyWord.last
# NaughtyWord Load (0.3ms) SELECT `naughty_words`.* FROM `naughty_words` ORDER BY `naughty_words`.`id` DESC LIMIT 1
#=> #<NaughtyWord id: 11, word: "word", must_review: true>
#irb(main):025:0> NaughtyWord.last.word
# NaughtyWord Load (0.6ms) SELECT `naughty_words`.* FROM `naughty_words` ORDER BY `naughty_words`.`id` DESC LIMIT 1
#=> nil
# irb(main):026:0> NaughtyWord.last["word"]
# NaughtyWord Load (0.6ms) SELECT `naughty_words`.* FROM `naughty_words` ORDER BY `naughty_words`.`id` DESC LIMIT 1
# => "word"
#irb(main):030:0> NaughtyWord.all.collect{|naughty_word| naughty_word["word"]}
# NaughtyWord Load (0.6ms) SELECT `naughty_words`.* FROM `naughty_words`
#=> ["word", "word", "word", "word", "word", "word", "word", "word", "word", "word", "word"]
如果我注释掉 attr_accessor 行,一切正常