如何在Ruby on Rails中向模型添加虚拟属性? [英] How to add a virtual attribute to a model in Ruby on Rails?
问题描述
我正在研究RubyonRails / ActiveAdmin应用程序。我的RoR版本是4.2.5,而AA版本是1.0.0。我有一个模型 Message
如下。
I'm working on a RubyonRails/ActiveAdmin application. My RoR version is 4.2.5 and AA version is 1.0.0. I have a model Message
as follows.
class Message < ActiveRecord::Base
belongs_to :user
validates :user, :content, presence: true
def palindrome
# return true/false
end
end
如您所见,我想要一个只读属性 palindrome
,该属性仅取决于邮件的内容
。我希望将此属性与普通属性完全一样。通常,我的意思是,当我通过 rails控制台
检索消息或请求 json
格式的消息时,我想看到一个列表中的 palindrome
属性。我还想通过此属性对消息进行过滤。
As you see, I want to have a read-only attribute palindrome
which only depends on the content
of message. I want this attribute to be treated exactly like a normal attribute. By normal, I mean when I retrieve messages via rails console
or request json
format of messages, I want to see a palindrome
attribute in the list. I would also like to have a filter for message by this attribute.
我不确定如何实现此目标。
I'm not sure how could I achieve this.
推荐答案
在模型中,您可以通过这种方式为虚拟属性 palindrome
属性编写属性访问器(读取器/写入器) :
In your model, you can write attribute accessors (reader/writer) for your virtual attribute palindrome
attribute this way:
# attr_reader
def palindrome
self[:palindrome]
end
# attr_writer
def palindrome=(val)
self[:palindrome] = val
end
# virtual attribute
def palindrome
#return true/false
end
而且,就像您使用Rails一样4,必须将 palindrome
属性与控制器中强参数定义中的任何其他模型属性一样,将其列入白名单,以便能够批量分配的值回文。像这样的东西:
And, as you are using Rails 4, you have to whitelist palindrome
attribute like any other model attribute in your strong param definition inside your controller in order to able to mass assign the value of palindrome
. Something like this:
# your_controller.rb
private
def your_model_params
params.require(:message).permit(:palindrome)
end
查看此有关虚拟属性的RailsCast 。虽然,它有点旧,但对于概念很有用。
Take a look at this RailsCast on Virtual Attributes. Although, it's a bit old, but would be useful for concepts.
注意:
虚拟属性不会自动显示在参数列表中。但是,您应该可以通过如下所示的Rails控制台访问它: Message.new.palindrome
。此外,您可以在JSON API中公开此虚拟属性,例如,如果您使用的是 Active Model Serializer ,可以在您的 MessageSerializer
中包含回文属性
,然后在回文中
将暴露给JSON API。
A virtual attribute will not show up in the param list automatically. But, you should be able to access it via Rails console like this: Message.new.palindrome
. Also, you can expose this virtual attribute in your JSON API, for example if you are using Active Model Serializer, you can have: attribute palindrome
in your MessageSerializer
and then palindrome
will be exposed to the JSON API.
这篇关于如何在Ruby on Rails中向模型添加虚拟属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!