简体   繁体   English

了解Ruby on Rails ActiveRecord模型访问器

[英]Understanding Ruby on Rails ActiveRecord model Accessors

My Model, "DataFile", has a bunch of fields which I'd like to set from outside the Model, eg 我的模型,“DataFile”,有一堆字段,我想从模型外部设置,例如

file = DataFile.new
file.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. 现在,据我所知,我必须在我的模型中放置一个“attr_accessor:field”,用于我想从外部修改的每个字段。 However, the above code runs fine without having any attr_accessors defined, setting the owner field to 123. Why is that? 但是,上面的代码运行正常,没有定义任何attr_accessors,将owner字段设置为123.为什么?

I'd expected to get a "method not defined" error or something like that. 我希望得到一个“方法未定义”错误或类似的东西。

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= . 因为Rails的ORM使用ActiveRecord模式,所以为与该表关联的数据库中的每个列自动创建两个方法: columnnamecolumnname = This happens "automatically" as a result of your model inheriting from ActiveRecord::Base. 由于您的模型继承自ActiveRecord :: Base,这会“自动”发生。 These methods are defined using ruby's metaprogramming facilities and are created dynamically at the time of class creation. 这些方法是使用ruby的元编程工具定义的,并且是在创建类时动态创建的。

For more info as to exactly what's going on, I would take a look at the Rails source. 有关确切内容的更多信息,我将查看Rails源代码。 However, the above is probably enough to give you a working understanding of what is happening. 但是,上述内容可能足以让您对正在发生的事情有所了解。

Drew and Zepplock got it right, but I'll just add one more thing. Drew和Zepplock做对了,但我还要补充一点。 The accessors that Rails (actually, ActiveRecord) creates for database fields are NOT Ruby accessors, and if you use script/console you'll see that owner isn't an instance variable of the object file. Rails(实际上,ActiveRecord)为数据库字段创建的访问器不是Ruby访问器,如果使用脚本/控制台,您将看到所有者不是目标文件的实例变量。

It's likely you'd never notice this until you venture away from the standard accessors and try to manipulate @owner inside a method on file. 在您远离标准访问器并试图在文件中的方法中操作@owner之前,您可能永远不会注意到这一点。 If you're learning Ruby at the same time you're learning Rails (which is what I did), it's likely you'll bump into this at some point. 如果你在学习Rails的同时学习Rails(这就是我所做的),那么你可能会在某些时候遇到这个问题。 This is the reason that you need to write: 这就是你需要写的原因:

class MyClass < ActiveRecord::Base
  def invalidate_owner
    self.owner = owner << " no longer owns this"
    save
  end
end

instead of 代替

class MyClass < ActiveRecord::Base
  def invalidate_owner
    self.owner << " no longer owns this"
    save
  end
end

Most likely "owner" is part of your database model. 很可能“所有者”是数据库模型的一部分。 The accessors for the database fields are auto-generated for you. 将自动为您生成数据库字段的访问者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM