【问题标题】:Rails .where syntax [closed]Rails .where 语法
【发布时间】:2012-12-10 21:03:35
【问题描述】:

我在使用 rails 中的 .where 语句时遇到了一些问题。有人可以帮忙吗?

<% due_late = project.tasks.where(":date_due < ?", Date.today).count %>

【问题讨论】:

    标签: sql ruby-on-rails ruby where


    【解决方案1】:

    date_due 在此上下文中是数据库中定义的列名,而不是 Ruby 符号 :date_due

    <% due_late = project.tasks.where("date_due < ?", Date.today).count %>
    #---------------------------------^^
    

    cmets 后更新

    如果两个表具有相同的列名,则需要在 JOIN 查询中区分表名:

    # Assuming it is tasks.date_due you are testing, rather than phases.date_due
    <% due_late = project.tasks.where("tasks.date_due < ?", Date.today).count %>
    

    作为建议,与其在视图 .erb 文件中执行此计算,不如在模型中创建一个返回值的方法。

    def due_late
      tasks.where("tasks.date_due < ?", Date.today).count
    end
    

    在视图中称为

    <%= project.due_late %>
    

    【讨论】:

    • 我最初也是这么想的。但是当我删除冒号时,我得到这个:“SQLite3::SQLException: 不明确的列名:date_due: SELECT COUNT(*) FROM "tasks" INNER JOIN "phases" ON "tasks"."phase_id" = "phases"。” id" WHERE "phases"."project_id" = 4 AND (date_due
    • @NathanHackley 那是因为您必须在两个连接表中具有相同的列。您需要使用表名。
    • 谢谢!创建方法的代码在哪里?在帮助文件中?另外,从我的角度来看,我该如何调用呢?
    • @NathanHackley 它将进入项目模型。看看我上面在视图中调用它的最后一行(假设 project 是您的 Project 类的一个实例)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2019-12-03
    • 1970-01-01
    相关资源
    最近更新 更多