新手问题 ActiveRecord 虚拟属性 (Virtual Attribute) 的问题

ljdam · 2013年08月26日 · 最后由 messiahxu 回复于 2013年08月31日 · 2601 次阅读

model 代码如下:

class Customer < ActiveRecord::Base
attr_accessible :visittime  #其他属性忽略

#下面的distince变量为虚拟属性
  def distince
    @distince
  end

  def distince=value
    @distince = value
  end

代码如上,distince 属性不需要入库,仅用于表示当前时间和 creatDate 的时间间隔,用于页面展示。 controller 代码如下:

@customers = Customer.all
 if @customers
     @customers.each{
       |customer| 
       distince=Rational(DateTime.parse(Time.new.strftime("%Y-%m-%d")) - DateTime.parse(customer.visittime)).to_i
       customer.distince = distince
     }
     respond_to do |format|
       format.xml { render xml: @customers }
     end
   end

在获取 xml 格式的返回时,distince 属性未能写入到 xml 中,求如何能够将 distince 属性写入到返回的 xml 中

@custom.to_xml methods: [:distince]

感谢回复,不过不太清楚这个代码的意思,能稍微详细点吗?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号