ActiveRecord :: StatementInvalid SQLite3 :: SQLException:没有这样的列:true:

我希望@messages返回@folder.messages,其中“已删除”列的值不等于true。 我不确定为什么这会继续抛出SQLException。 我想我没有正确格式化已删除的属性,但我不确定如何解决它。

任何帮助将不胜感激。 提前致谢。

错误信息:

ActiveRecord::StatementInvalid in MailboxController#index SQLite3::SQLException: no such column: true: SELECT "message_copies".* FROM "message_copies" WHERE ("message_copies".folder_id = 1) AND (deleted != true) 

应用跟踪:

 app/controllers/mailbox_controller.rb:14:in `show' app/controllers/mailbox_controller.rb:5:in `index' 

Mailbox_Controller.rb

 1 class MailboxController  "show" 7 end 8 9 def show 10 current_user = User.find(session[:user_id]) 11 @folder = Folder.where("user_id = #{current_user.id}").first 12 @msgs = @folder.messages 13 @ms = @msgs.where("deleted != true") 14 @messages = @ms.all.paginate :per_page => 10, 15 :page => params[:page], :include => :message, 16 :order => "messages.created_at DESC" 17 end 18 end 

SQLite使用C风格的布尔值 :

SQLite没有单独的布尔存储类。 相反,布尔值存储为整数0(假)和1(真)。

所以,当你这样说时:

 deleted != true 

SQLite不知道它是什么,所以它假设你试图引用另一个列名。

处理这个问题的正确方法是让AR将你的Ruby boolean转换为SQLite布尔值(如Tam和fl00r的答案)。 我认为知道你做错了什么是有用的。

更新 :如果你想检查非真实deleted并包含NULL,那么你会想要这个:

 @ms = @msgs.where("deleted != ? OR deleted IS NULL", true) 

或者更好的是,根本不允许deleted NULL。 你不应该允许NULL是任何列,除非你绝对必须(ActiveRecord的默认值为nullability与它应该是完全相反)。 SQL NULL是一个奇怪的野兽,你总是要特别对待它,除非你需要一个列的“not there”或“unspecified”值,否则最好不要允许它。

 @ms = @msgs.where("deleted != ?", true) # OR @ms = @msgs.where(:deleted => false) 

true对于不同的数据库是不同的。 在某些情况下,它是t/f值,并且在某些true/false ,所以你应该将它放在引号中并确定它是否适合你的特定数据库,或者你应该将它从你的sql中排除,所以Rails会这样做为你工作。

UPD

如果deletedNULL 。 第一。 默认情况下,将删除的字段设置为false 。 二,如何用AR找到它:

 @ms = @msgs.where("deleted = ? OR deleted = ?", false, nil) # wich won't work, Thanks to @mu is too short @ms = @msgs.where("deleted = ? OR deleted IS NULL", false) 

尝试

 @ms = @msgs.where(["deleted != ?",true])