[英]Adding fields to a Rails model without saving them in the database in Rails
我正在基於表示Rails模型的JSON對象渲染視圖。 這個JSON對象需要的字段不是Rails模型的一部分,因此我將它們添加到控制器中,如示例1所示:
#Controller
events = Event.where(<query>).each do |event|
event[:duration] = (event.end - event.start)/3600
event[:datatime] = event.start.hour + event.start.min/60.0
...
end
render json: events
這樣可以正確渲染我的數據。 但是,我收到以下棄用警告:
DEPRECATION WARNING: You're trying to create an attribute `duration'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc.
我想重寫我的代碼以避免此警告。 如果我嘗試將這些多余的字段視為標准對象屬性,則這些值將無法正確呈現。 下面是我嘗試使用標准對象屬性的嘗試:
#Controller
events = Event.where(<query>).each do |event|
event.duration = (event.end - event.start)/3600
event.datatime = event.start.hour + event.start.min/60.0
...
end
render json: events
#Model
class Event < ActiveRecord::Base
include ActiveModel::AttributeMethods
attr_accessor :duration, :datatime
這將導致字段用undefined
填充。 如果我使用attr_writer
而不是attr_accessor
, attr_accessor
。 我該如何解決這個問題? 是我被迫將這些臨時屬性存儲在數據庫中還是只是使用了錯誤的語法?
如果要讀寫訪問器,請使用attr_accessor
:
class Event < ActiveRecord::Base
attr_accessor :duration, :datatime
end
您不需要包括ActiveModel::AttributeMethods
即可利用attr_accessor
。
要將訪問器包括在JSON中,請告訴render包括它們:
render json: events, methods: [:duration, :datatime]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.