本文介绍了在同一字段上使用attr_accessor和attr_accessible的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码在后台会发生什么?

What happens in the background with the following code?

class User < ActiveRecord::Base

 attr_accessor :name
 attr_accessible :name

end

提示:实例化该类时,它将持久化到数据库中吗?为什么或为什么不呢?

Hint: When instantiating the class, will it be persisted to the database? Why or why not?

推荐答案

感谢大家的快速解答!我认为,您的回答加在一起,为我提供了理解此难题所需的知识.

Thanks everyone for quick answers!Your answers combined gave me the pieces I needed to understand this puzzle, I think.

(在一个相关的问题中,我遇到了很多nil错误,例如对象不支持#inspect"和"nil:NilClass的未定义方法'keys".共有att_accessor字段.)

(In a related problem, I was getting a lot of nil errors like "Object doesn’t support #inspect", and "undefined method ‘keys’ for nil:NilClass". I managed to solve it now, by removing the att_accessor field altogether.)

通过试验这种特殊情况,这是我发现的:

By experimenting with this particular case, this is what I've found out:

实际上,:name字段不会保留到数据库中.

Actually, the :name field won't be persisted to the database.

user = User.new(:name=>"somename")

将仅在对象上设置属性,而不会将:name列保留到数据库中.就像下面的"rails console"输出所示:

Will only set the attribute on the object, but not persist the :name column to the database. Like the following 'rails console' output shows:

> user
=> <User id: nil, created_at: nil, updated_at: nil>
> user.save
=> true
> user
=> <User id:1, created_at: 2011-01-19 12:37:21, updated_at: 2011-01-19 12:37:21>

我认为这是因为* attr_accessor所做的设置器将覆盖ActiveRecord的设置器*(这将照顾数据库的持久性).您仍然可以从对象的:name字段中检索值,如下所示:

I assume this is because *the setter made by attr_accessor will override ActiveRecord's setter* (which takes care of the database persistence). You can still retrieve the value from the :name field from the object though, like this:

> user.name
=> "somename"

因此,总而言之,我了解到在字段上使用attr_accessor可能导致它们无法持久保存到数据库中.虽然我认为attr_accessible描述了应该从外部访问的数据库中的字段,但在这种情况下似乎没有什么不同.

So, in conclusion, I've learnt that using attr_accessor on fields might lead to them not being persisted to the database. And while I thought attr_accessible describes fields in the database that should be accessible from the outside, it doesn't seem to make a difference in this case.

这篇关于在同一字段上使用attr_accessor和attr_accessible的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 05:41