提问人:CafeHey 提问时间:11/16/2023 更新时间:11/16/2023 访问量:100
在 Rails 中,如何向属性/列添加“helper”方法?[关闭]
In Rails how I add a "helper" method to an attribute / column? [closed]
问:
假设我们有一个名为“Items”的表,一个名为“name”的列和一个名为“quantity”的列。
然后假设我们有一个这样的项目实例:
@item = Item.first
在此实例上,您可以调用方法,例如:
@item.name.present?
@item.quantity.is_a?(Integer)
我将如何将自己的方法添加到所有列中,例如,如果我想调用:
@item.name.custom_method?
@item.quantity.custom_method?
@item.name.custom_method_2(:xyz)
@item.quantity.custom_method_2(:xyz)
因此,我想将方法添加到所有列属性中,每个属性都用它做一个自定义的事情。我已经看到了它的一些宝石,例如,Rails 用 dirty 来做它并添加到列/属性中。changed?
答:
4赞
Alex
11/16/2023
#1
您可以定义所谓的属性方法,而属性方法又会为所有属性定义方法:
# app/models/model.rb
class Model < ApplicationRecord
attribute_method_suffix "_is_custom?"
private
def attribute_is_custom? attr
"#{attr} is custom."
end
end
>> Model.first.name_is_custom?
=> "name is custom."
>> Model.first.id_is_custom?
=> "id is custom."
https://api.rubyonrails.org/classes/ActiveModel/AttributeMethods.html
评论
@item.name
String
present?
String
Object
ActiveRecord::Dirty
changed?
XXXX_changed?