2

有没有办法通过 ActiveRecord 访问“real_field”(比方说)?

例如。如果我有一个 Model Company 并使用Company.create(name: "My Company Name")(with I18n.locale = :en),则该名称值不会保存在 Company 记录中,而是保存在字符串的 Mobility 表中。

这样做Company.last会返回

#<Company id: 5, name: nil>

但是这样做Company.last.name会返回我的公司名称(假设语言环境设置正确)

有没有办法做这样的事情Company.last.real_name会给我记录的实际价值?在这种情况下为零。我也想拥有一个real_name=

移动性 (0.4.2) i18n (>= 0.6.10, < 0.10) request_store (~> 1.0)

后端:key_value

4

2 回答 2

2

尝试这个:

Company.last.read_attribute :name

或这个:

Company.last.name_before_type_cast
于 2018-02-07T14:39:55.087 回答
2

作为任何 ActiveRecord 模型的一般方法,接受的答案是正确的:read_attribute并且write_attribute将始终获取和设置列值,而不管模型中定义的任何覆盖。正如我评论的那样,这些方法也有简写:

company[:name]         #=> returns the value of the name column
company[:name] = "foo" #=> sets the value of the name column to "foo"

此外,特别是在 Mobility 中,您可以将一个选项传递给 getter(和 setter),该选项将跳过Mobility通常对属性执行的任何操作:

company.name(super: true) # skips Mobility and goes to its parent (super) method,
                          # which would typically be the column value.

在您可能正在使用另一个对属性也有特殊作用的 gem 的情况下,这种方法可能会更好。

还有一个 setter 选项,但是使用起来有点棘手:

company.send(:name=, "foo", super: true) # sets name to "foo", skipping Mobility

如果您将 Mobility 与另一个覆盖属性 getter 和/或 setter 的 gem 一起使用,那么该super选项可能很有用;否则读/写属性可能没问题。

于 2018-02-10T02:23:03.873 回答