2014-08-30 51 views
0

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」,但在數據庫中仍爲空。

回答

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命令。

目前,你的「無規定」的數據僅僅是空白 - 不爲空

0

當註釋沒有用戶時,它看起來有空白的user_id列。所以,正確的查詢應該是

@post = Post.find(1) 
@comments = @post.comments.where("user_id != ''") 
0

我的代碼可能無法代表一個標準的方式,但它會在兩種情況下(空和空白)工作。

@post = Post.find(1) 
@comments = @post.comments.where("user_id > 0")