获取所有没有空字段的记录
问题描述:
Posts
有很多Comments
。每个Comment
可选地属于User
。获取所有没有空字段的记录
我如何获得有1个用户的帖子1的所有评论?
Comments
content post_id user_id
------- ------- -------
There is no user for this post. 1
This is an example with a user. 1 123
Another example with a user. 1 8321
事情我已经尝试:
这不返回任何记录
@comments = Post.find(1).comments.where(:user_id != nil)
这些返回的每条记录:
@comments = Post.find(1).comments.where("user_id IS NOT NULL")
@comments = Post.find(1).comments.where("user_id <> 0")
当我打印出来的user_ids在页面上,它看起来就像零读写为“0”,但在数据库中仍为空。
答
我应该这样做:
#app/models/post.rb
class Post < ActiveRecord::Base
has_many :comments do
def no_user
where.not(user_id: "") #-> http://robots.thoughtbot.com/activerecords-wherenot
end
end
end
#app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
end
这将允许我这样称呼:
#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def show
@post = Post.find params[:post_id]
@comments = @post.comments.no_user
end
end
-
上的注意事项空
有null
是一个特定的数据类型在数据库中
我们希望“默认”填充表的列时使用它 - 让你提交的数据,具有数据库尽可能有效地提供正确的数据分配。
我一定会look up about the NULL
data type与喜欢的MYSQL & PGSQL。这将使您能够将任何未填充的数据列定义为NULL
- 允许您调用NOT NULL
命令。
目前,你的“无规定”的数据仅仅是空白 - 不为空
答
当注释没有用户时,它看起来有空白的user_id列。所以,正确的查询应该是
@post = Post.find(1)
@comments = @post.comments.where("user_id != ''")
答
我的代码可能无法代表一个标准的方式,但它会在两种情况下(空和空白)工作。
@post = Post.find(1)
@comments = @post.comments.where("user_id > 0")