了解Ruby on Rails ActiveRecord模型访问器

编程入门 行业动态 更新时间:2024-10-28 14:23:45
本文介绍了了解Ruby on Rails ActiveRecord模型访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的模型"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模型访问器

本文发布于:2023-10-28 22:33:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537965.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   Ruby   Rails   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!