为没有 `attr_accessor` 的 Rails 模型设置非数据库属性 [英] Set non-database attribute for rails model without `attr_accessor`

查看:46
本文介绍了为没有 `attr_accessor` 的 Rails 模型设置非数据库属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中,我可以为模型设置一个属性(不是数据库中的列).例如(PHP代码),

In PHP, I can set an attribute (that is not a column in database) to a model. E.g.(PHP code),

$user = new User;
$user->flag = true;

但是在 Rails 中,当我设置数据库中不存在的任何属性时,它会抛出错误 undefined method flag.有 attr_accessor 方法,但是如果我需要大约十个临时属性会怎样?

But in rails, when I set any attribute that doesn't exist in database, it will throw an error undefined method flag. There is attr_accessor method, but what will happen if I need about ten temp attributes?

推荐答案

这是意料之中的,因为它是 ActiveRecord 的设计方式.如果您需要设置任意属性,则必须使用不同类型的对象.

This is expected because it's how ActiveRecord works by design. If you need to set arbitrary attributes, then you have to use a different kind of objects.

例如,Ruby 提供了一个名为 OpenStruct 允许您创建可以分配任意键/值的对象.您可能希望使用此类库,然后仅在需要保存到数据库时才将对象转换为相应的 ActiveRecord 实例.

For example, Ruby provides a library called OpenStruct that allows you to create objects where you can assign arbitrary key/values. You may want to use such library and then convert the object into a corresponding ActiveRecord instance only if/when you need to save to the database.

不要尝试将 ActiveRecord 建模为您刚刚描述的行为,因为它根本不是设计为以这种方式运行的.根据您目前的 PHP 知识,这将是一个 cargo culting 错误.

Don't try to model ActiveRecord to behave as you just described because it was simply not designed to behave in that way. That would be a cargo culting error from your current PHP knowledge.

这篇关于为没有 `attr_accessor` 的 Rails 模型设置非数据库属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆