【问题标题】:Calculate and display user age in the view计算并在视图中显示用户年龄
【发布时间】:2019-09-03 22:54:57
【问题描述】:

我有一个date_field :born_in 年龄,我想在用户个人资料中显示计算出的用户年龄,而不是常规日期格式mm/dd/yyyy

我在这个答案中找到了关于如何计算用户年龄的method,但我不知道如何在我的 Rails 应用程序中实现它。

user_information.rb

class UserInformation < ApplicationRecord
  belongs_to :user

  has_one :gender, :dependent => :destroy
  accepts_nested_attributes_for :gender, :allow_destroy => true

  has_one :relationship, :dependent => :destroy
  accepts_nested_attributes_for :relationship, :allow_destroy => true
end

show.html.erb

<%= @user.user_information.try(:born_in) %>

【问题讨论】:

  • 你试过什么?你的用户模型是什么样的?
  • @moveson 我已将我的模型包含在我的问题中

标签: ruby-on-rails ruby


【解决方案1】:

将方法作为属性(实例函数而不是类函数)放入模型中,然后在表单中将结果弹出到页面中。你没有显示任何代码,所以我不能给你一个代码示例来解决你的问题,但可能是这样的

class Person ...
  ...

  def calculated_age
    now = Time.now.utc.to_date
    now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
  end

那么在你看来

<%= @person.calculated_age #Or whatever your instance variable name is %>

您可能还想添加一个检查 dob 不为 null 并在模型中设置适当的默认值

这正是模型的用途。视图应该只呈现它们提供的信息 下次显示更多代码并帮助人们帮助您。

【讨论】:

  • 我已经更新了我的问题并包含了我的嵌套模型来设计用户模型。我收到了这个错误undefined local variable or method dob' #<0x00007feccd3a0d60>
【解决方案2】:

在我尝试@jamesc 解决方案之前:

def calculated_age
    now = Time.now.utc.to_date
    now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
  end

但我收到一条错误消息:

undefined local variable or method dob' for #&lt;UserInformation:0x00007feccd3a0d60&gt;

那是因为计算方法中没有定义dob。

这是我想出的解决方案:

def age
    now = Time.current
    dob = self.born_in
    now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
  end

在用户个人资料show.html.erb 我所要做的就是:

<%= @user.user_information.age %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 2017-05-26
    • 2017-08-08
    • 2012-03-26
    相关资源
    最近更新 更多