如何在 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
,它只依赖于消息的content
.我希望这个属性被完全像一个普通属性一样对待.通常,我的意思是当我通过 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 on Virtual Attributes.虽然有点旧,但对概念很有用.
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,您可以有: attribute palindrome
在您的 MessageSerializer
中,然后 palindrome
将暴露给 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屋!