ruby-on-rails - 如何为模型呈现非数据库变量?
问题描述
我有一个模型Event
,它有一些存储在数据库中的属性和其他未存储的属性。我用 attr_accessor 做到这一点。
class Event < ApplicationRecord
attr_accessor :name, :location, :description
end
当我渲染一个事件数组时render json: @events
,只显示存储的属性(例如 id、created_at、updated_at、points...)。如何还显示非数据库变量/属性(例如名称、位置和描述)?
解决方案
使用attribute
. 这可以用来覆盖 Rails 解释数据库列的选择,也可以用来添加非列属性。
它需要一个名称和一个可选类型。你也可以给一个默认值。
class Event < ApplicationRecord
attribute :name
attribute :location
attribute :description, default: "Probably another music festival"
end
推荐阅读
- python - 当原始变量更新时,如何设置依赖于另一个变量的变量来更新?
- python - CommandInvokeError:命令引发异常:RuntimeError:在另一个循环正在运行时无法运行事件循环嗅探数据包时
- javascript - 如何修复与获取的数据不同的 Postman 数据
- flask - 有什么方法可以将 Flask 会话存储在本地存储中而不是 cookie 中?
- windows - Apache Cassandra 进程在 Windows 上是如何命名的?
- r - 如何更改R中矩阵中列的顺序
- java - 尝试使用 Java (Android Studio) 从 String 创建 JSONObject
- javascript - 如何在while循环中串联promise
- sql-server - 使用 Docker 连接的 SQL Server 的物理文件夹
- swift - 如何在 Swift 中使用变量编写 SQL Select Query?