【问题标题】:Rails 4.1, Ruby 2.1, Devise, Why 'syntax error, unexpected tConstant' in my .where() with multiple conditions?Rails 4.1,Ruby 2.1,Devise,为什么在我的 .where() 中出现“语法错误,意外 tConstant”,有多个条件?
【发布时间】:2015-04-17 05:47:30
【问题描述】:

我从类似的帖子中看到,这通常是前一行缺少某些结束字符的情况,但我在这里看不到。 Courses 资源嵌套在 Schools 中,我可以打印出 user_id 和 school.id。

错误似乎出现在具有多个条件的 Course.where 子句中(user_id: current_user.id AND school_id: @school.id) 上面的单条件 where 子句似乎工作得很好。

courses_controller.rb

class CoursesController < ApplicationController

  before_action :set_school

  helper_method :calculated_grade_stub


  # GET /courses
  # GET /courses.json
  def index
    if @school.nil?
      @courses = Course.where(user_id: current_user.id)
    else
      @courses = Course.where(user_id: current_user.id AND school_id: @school.id)
    end
  end

【问题讨论】:

    标签: mysql ruby-on-rails ruby ruby-on-rails-4 devise


    【解决方案1】:

    操作员是&amp;&amp;and,而不是AND

    但是,这不是问题的根本原因:您似乎对 Hash 文字的一般语法感到困惑。 Hash 文字中的条目由逗号分隔,而不是由运算符分隔:

    @courses = Course.where(user_id: current_user.id, school_id: @school.id)
    

    还要注意if 是一个表达式,因此会返回一个值,因此您可以轻松地将该方法重构为

    def index
      @courses = if @school.nil?
        Course.where(user_id: current_user.id)
      else
        Course.where(user_id: current_user.id, school_id: @school.id)
      end
    end
    

    【讨论】:

    • 谢谢,但我都试过了。没有改变错误。
    • 它应该改变错误。现在应该是unexpected tLABEL。这应该给您一个潜在问题的提示,即您并不真正了解 Hash 文字是如何工作的,然后,当您考虑如何编写 Hash 文字时,您应该意识到 @987654332 中的条目@ 文字由逗号分隔,而不是运算符。
    【解决方案2】:

    你可以试试这个:

      @courses = Course.where('user_id = ? AND school_id = ?',current_user.id , @school.id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 2022-01-18
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      相关资源
      最近更新 更多