【问题标题】:ActionView::Template::Error (PG::UndefinedColumn: ERROR: column does not exist)ActionView::Template::Error (PG::UndefinedColumn: ERROR: 列不存在)
【发布时间】:2017-03-14 10:03:47
【问题描述】:

型号

尝试 1

def challenge_date
   deadline || date_started  
end

尝试 2

def challenge_date
  if deadline != date_started
    [deadline, date_started].reject(&:blank?).join()
  else
    date_started
  end
end

两次尝试都报错。我需要方法来遍历next_user_challenge

def next_user_challenge
  user.challenges.where('challenge_date > ?', challenge_date).order('challenge_date ASC').first
end

导轨 c

# some challenges will just have a deadline
 id: 1,
 name: "Publish a Novel",
 deadline: Sat, 26 Nov 2016,
 date_started: nil,
 user_id: 117,

# some challenges will just have a date_started
 id: 2,
 name: "Write a Chp",
 deadline: nil,
 date_started: Thu, 20 Oct 2016,
 user_id: 117,

# and some challenges will have both
 id: 3,
 name: "Run a Mile",
 deadline: Thu, 26 Sep 2016,
 date_started: Thu, 26 Sep 2016, # If challenge has both deadline and date_started then date_started will be the same date as the deadline
 user_id: 117,

【问题讨论】:

  • challenge_date 是一种方法,所以你不能对它进行数据库查询。在比较有开始日期的挑战和有截止日期的挑战时,如何确定下一个挑战是什么?
  • next_user_challenge 是您的 User 模型上的方法吗?您能否说明一下您希望将哪个日期与挑战的截止日期/开始日期进行比较?

标签: ruby-on-rails ruby


【解决方案1】:

不是 postgres 查询,但您可以通过 rails 方式实现它

def next_user_challenge
  user.challenges.select{ |ch| ch.challenge_date > challenge_date }.sort_by(&:challenge_date).first
end

注意:这将从 db 获取所有挑战,然后选择有效的挑战。

我会建议在挑战表中创建一个新列并使用 ActiveModal 回调来更新它。

【讨论】:

    【解决方案2】:

    您使用非数据库模型属性来查询数据,当然它不会工作。

    解决这个问题,有两种方法:

    1. 使用Deepak方式

    2. 使用原始SQL查询,这样,你应该准备challenge_date并加入自己的表来处理其他查询。

    【讨论】:

      猜你喜欢
      • 2015-05-11
      • 2019-09-21
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多