【问题标题】:Rails: Where clause doesn't work in any conditionRails:Where子句在任何情况下都不起作用
【发布时间】:2012-09-11 08:31:13
【问题描述】:

由于一个简单的 Rails where 查询,我快要失去理智了。我根本无法理解为什么它在 10 行前确实可以工作,而在它之后却没有。我无法弄清楚可能导致问题的原因

@userID = Token.where(:tokenCode => @tokenReceived)
  #@init.tokenCode=@tokenReceived+"1" #randomize algorithm required!
  @init.tokenCode=@codeGenerated=generate_activation_code()
  if @userID.nil?
    @newToken=Token.new
    @newToken.tokenCode=@codeGenerated
  else
    @tokenToAdd = "12"
    @newToken=Token.where(:userID => "1")
    #if @newToken.nil?
      @newToken.tokenCode="12"
    #end
  end
  #@newToken.save  
  @init.save

当我成功地向“http://localhost:3000/inits.json”发出 JSON 请求时,它会给我一个包含大量错误的页面,但我认为其中的主要错误是:

<h1>
  NoMethodError
    in InitsController#create
</h1>
<pre>undefined method `tokenCode=&#x27; for #&lt;ActiveRecord::Relation:0x007fc43cb40b88&gt;</pre>

可能是什么原因?我写的where子句都错了吗?

编辑:当我激活 if 子句时,它起作用了。我只是相信@newToken 对象是空的,但是我几乎不可能发现原因。我的 Token 表中有一个 userID 为 1 的数据。

【问题讨论】:

    标签: ruby-on-rails select rails-activerecord crud


    【解决方案1】:

    当你这样做时:

     @newToken=Token.where(:userID => "1")
    

    你得到一个ActiveRecord::Relation,但你期望的是一个对象。所以只需将其替换为:

     @newToken=Token.where(:userID => "1").first
    

    【讨论】:

    • 感谢您的出色回答!你救了我的命。
    猜你喜欢
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多