首页 > 解决方案 > 如何为模型呈现非数据库变量?

问题描述

我有一个模型Event,它有一些存储在数据库中的属性和其他未存储的属性。我用 attr_accessor 做到这一点。

class Event < ApplicationRecord
 attr_accessor :name, :location, :description
end

当我渲染一个事件数组时render json: @events,只显示存储的属性(例如 id、created_at、updated_at、points...)。如何还显示非数据库变量/属性(例如名称、位置和描述)?

标签: ruby-on-rails

解决方案


使用attribute. 这可以用来覆盖 Rails 解释数据库列的选择,也可以用来添加非列属性。

它需要一个名称和一个可选类型。你也可以给一个默认值。

class Event < ApplicationRecord
 attribute :name
 attribute :location
 attribute :description, default: "Probably another music festival"
end

推荐阅读