将属性写入活动记录对象 [英] Write attribute to active record object

查看:35
本文介绍了将属性写入活动记录对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在将属性返回给客户端之前将其写入活动记录对象.

I'm trying to write an attribute to an active record object before returning it to the client.

user = User.find(18).profile

然后我想设置 user[:random_attribute] = 'random_attribute'

但我收到以下错误消息

ActiveModel::MissingAttributeError(不能写未知属性random_attribute'):

在将随机数据返回给客户端之前将随机数据添加到记录的最佳方法是什么?

what's the best way to add random data to a record before returning it to the client?

推荐答案

好像你需要的是一个虚拟属性(关于 ActiveRecord 虚拟属性的资料相当多).

Seems like what you need is a virtual attribute (there is quite a lot of information about ActiveRecord virtual attributes).

class User < ActiveRecord::Base
  def random_attribute
    # ...
  end
end

如果您想在代码中的其他位置分配 random_attribute 值,您可以使用 attr_accessor<定义相应的 getter 和 setter 方法,就像在任何其他 Ruby 类中一样/代码>.

If you want to assign the random_attribute value somewhere else in your code, you can do so by defining the corresponding getter and setter methods just like in any other Ruby class by using attr_accessor.

class User < ActiveRecord::Base
  attr_accessor :random_attribute
end

a = User.new
a.random_attribute = 42
a.random_attribute # => 42

另一种定义 getter 和 setter 方法的方法(以防您需要更复杂的东西):

Another way to define the getter and setter methods (in case you might need something more sophisticated):

class User < ActiveRecord::Base
  def random_attribute(a)
    @random_attribute
  end

  def random_attribute=(a)
    @random_attribute = a
  end
end

请记住,在序列化期间,默认情况下不会包含该属性,因此如果您需要在 json 中使用此属性,您可能需要将相应的参数传递给 to_json 方法.

Keep in mind though that during serialization, that attribute won't be included by default, so if you need this attribute in json, you might have to pass the corresponding arguments to the to_json method.

puts a.to_json(methods: [:random_attribute])
# => { ... "random_attribute":42}

这篇关于将属性写入活动记录对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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