attr_accessor,无法访问属性 [英] attr_accessor, not able to access property
问题描述
这可能是一个非常愚蠢的问题,但我们开始
This is probably very stupid question but here we go
class Foo < ActiveRecord::Base
attr_accessor :group_id
end
来自irb
# gets record which has group_id set to 106
foo = Foo.find(1)
foo.group_id
=> nil
如果我去删除
attr_accessor :group_id
attr_accessor :group_id
一切正常
foo = Foo.find(1)
foo.group_id
=> 106
我的问题是为什么?不应该 attr_accessor 为属性 :group_id 创建访问器/修改器,这就是为什么所有这些都应该工作的原因.我错过了什么?
My question is why? Shouldn't attr_accessor create accessor / mutator for property :group_id and that why all should be working. What am I missing?
更新
下面是很好的答案,就像我在这里的动机的解释一样,我想使用某些属性的批量分配(从 Rails 3.2.x 开始你需要这个).为此,您需要 attr_accessible ,我发现这样的代码更清晰,当然,如果负责任地使用:)
Good answers bellow, just as explanation for my motivation here is I want to use mass assignment of certain properties (you need this since Rails 3.2.x). For that you need attr_accessible , I find that code is much cleaner that way, of course if used responsibly :)
推荐答案
看起来 group_id
已经是你的 Foo
对象的一个属性(通过它返回的事实表明106 当 attr_accessor
被省略时).通过添加attr_accessor
,您将覆盖已有的内容并创建一个名为group_id
的方法读取器和写入器.新定义的 group_id
的返回为零,因为您没有定义任何东西.
Looks like group_id
is already a property on your Foo
object (shown by the fact that it returns 106 when attr_accessor
is omitted). By adding attr_accessor
you are overriding what's already there and creating a method reader and writer called group_id
. The return of the newly defined group_id
is nil since you don't define anything.
从概念上讲,你会得到这样的结果:
Conceptually, you're ending up with something like this:
class Foo < ActiveRecord::Base
def group_id # overriding previous definition of 'group_id'
nil
end
end
<小时>
如果您的目标是公开属性,那么是的,请使用 attr_accessible
If your goal is expose properties then yes, use attr_accessible
这篇关于attr_accessor,无法访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!