我的模型"DataFile"具有一堆字段,例如,我想从模型外部进行设置.
My Model, "DataFile", has a bunch of fields which I'd like to set from outside the Model, e.g.
file = DataFile.new file.owner = 123现在,据我所知,对于我想从外部修改的每个字段,我都必须在模型中放置一个"attr_accessor:field".但是,上面的代码在没有定义任何attr_accessors的情况下运行良好,将owner字段设置为123.为什么?
Now, as far as I know, I'd have to place an "attr_accessor :field" in my model, for every field that I'd like to modify from outside. However, the above code runs fine without having any attr_accessors defined, setting the owner field to 123. Why is that?
我希望收到未定义的方法"错误或类似的信息.
I'd expected to get a "method not defined" error or something like that.
推荐答案由于Rails的ORM使用ActiveRecord模式,因此会为与该表关联的数据库中的每一列自动创建两种方法: columnname ,以及 columnname = .由于您的模型是从ActiveRecord :: Base继承而来的,因此会自动"发生.这些方法是使用ruby的元编程工具定义的,并在创建类时动态创建.
Because Rails' ORM uses the ActiveRecord pattern, two methods are created automatically for each column in the database associated with that table: columnname, and columnname=. This happens "automatically" as a result of your model inheriting from ActiveRecord::Base. These methods are defined using ruby's metaprogramming facilities and are created dynamically at the time of class creation.
有关发生了什么的更多信息,请看一下Rails源码.但是,以上内容可能足以使您对正在发生的事情有一个实际的了解.
For more info as to exactly what's going on, I would take a look at the Rails source. However, the above is probably enough to give you a working understanding of what is happening.
更多推荐
了解Ruby on Rails ActiveRecord模型访问器
发布评论