1

我以为我理解 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 行,一切正常

4

1 回答 1

1

I think you want to use attr_accessible instead of attr_accessor. The first is a Rails method to white label for mass assignment attributes so it's possible to use something like User.new params[:user] in your controller. The second one is plain Ruby, it's a helper to create both the read and write (aka getter and setter) methods for a given instance variable.

So what you are doing with attr_accessor is actually overriding the attribute accessor method made by ActiveRecord and that's why it returns nil.

于 2013-02-01T01:20:25.947 回答