问题描述
我再次使用 rails 并发现了这种行为,当我创建具有某些属性的 Post 模型的新实例时,它告诉我所有属性都为零,为什么会发生这种情况?
I'm playing with rails again and found this behavior, when i create a new instance of a Post model with some attributes it tells me that all attributes are nil, why it is happening?
Loading development environment (Rails 4.0.0)
2.0.0-p451 :001 > a = Post.new(title: "Rails", content: "Rails Post")
=> #<Post id: nil, title: nil, content: nil, author: nil, rating: nil, created_at: nil, updated_at: nil>
2.0.0-p451 :002 > a.title
=> "Rails"
2.0.0-p451 :004 > a.content
=> "Rails Post"
2.0.0-p451 :005 > a.inspect
=> "#<Post id: nil, title: nil, content: nil, author: nil, rating: nil, created_at: nil, updated_at: nil>"
2.0.0-p451 :006 > a.errors.messages
=> {}
2.0.0-p451 :007 > a.valid?
=> true
class Post < ActiveRecord::Base
attr_accessor :title, :content, :author, :rating
end
推荐答案
您正在为所有属性定义 attr_accessor
,这是为同名实例变量定义 getter 和 setter 的快捷方式像这样:
You are defining attr_accessor
for all your properties, which is a shortcut for defining getters and setters for an instance variable of the same name like so:
def content
@content
end
def content=(new_content)
@content = new_content
end
Rails 还会为您的模型具有的每个数据库字段自动生成具有这些名称的方法.这些方法会相互冲突.
Rails will also auto-generate you methods with these names, for every database field that your model has. These methods will conflict with each other.
当您调用 post.content = 'foo'
时,不是调用 Rails 生成的方法,该方法将在内部将模型的 content
属性设置为 'foo',而是'正在调用 attr_accessor
定义的方法,该方法会将实例变量 @content
设置为 'foo'.
When you call post.content = 'foo'
, instead of calling the Rails-generated method that will internally set your model's content
attribute to 'foo', you're calling the attr_accessor
-defined method which will set the instance variable @content
to 'foo'.
inspect
的输出是迭代 Rails 定义的模型属性,而不是实例变量.
The output of inspect
is iterating over the Rails-defined model attributes, not the instance variables.
您是否真的想将这些属性声明为 attr_accessible
而不是 attr_accessor
?
Did you actually mean to declare these attributes as attr_accessible
instead of attr_accessor
?
这篇关于Rails 新对象为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!