7

我想让@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 < ApplicationController  
2     def index  
3       current_user = User.find(session[:user_id])  
4       @folder = Folder.where("user_id = #{current_user.id}").first  
5       show  
6       render :action => "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  
4

3 回答 3

20

SQLite 使用 C 风格的布尔值

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

所以,当你这样说时:

deleted != true

SQLite 不知道是什么true,因此它假定您正在尝试引用另一个列名。

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

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

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

或者更好的是,根本不允许 NULL deleted。你不应该允许 NULL 是任何列,除非你绝对必须这样做(ActiveRecord 的可空性默认值与它应该是完全相反的)。SQL NULL 是一种奇怪的野兽,您总是必须特别对待它,最好不要允许它,除非您需要列的“不存在”或“未指定”值。

于 2011-04-24T03:05:37.493 回答
3
@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)
于 2011-04-24T02:58:01.250 回答
0

尝试

@ms = @msgs.where(["deleted != ?",true])
于 2011-04-24T02:58:51.130 回答