2012-04-02 59 views
0

我已經設置了一個基本論壇。我希望posts#index行動只顯示parent_post_id爲零的記錄,因此不是回覆帖子。我已經安裝了squeel,但我不確定是否將它設置正確。ActiveRecord,只有帶有零父記錄的對象

#app/controllers/posts_controller.rb 
    def index 
    @forum = Forum.find(params[:forum_id]) 
    @posts = @forum.posts.where{ |post| post.thread == nil } 
    end 

#app/models/post.rb 
class Post < ActiveRecord::Base 
    has_many :replies, :class_name => "Post" 
    belongs_to :thread, :class_name => "Post", :foreign_key => "parent_post_id" 
end 

#config/initializers/squeel.rb 
Squeel.configure do |config| 
    # To load hash extensions (to allow for AND (&), OR (|), and NOT (-) against 
    # hashes of conditions) 
    config.load_core_extensions :hash 

    # To load symbol extensions (for a subset of the old MetaWhere functionality, 
    # via ARel predicate methods on Symbols: :name.matches, etc) 
    config.load_core_extensions :symbol 

    # To load both hash and symbol extensions 
    config.load_core_extensions :hash, :symbol 
end 

回答

1

嘗試

@posts = @forum.posts.where{ "posts.parent_post_id is null" } 

部分的 http://api.rubyonrails.org/classes/ActiveRecord/Base.html

條件我們說 「上崗」 不 「後」,因爲表的名稱是 「上崗」

已添加對於此類簡單的where子句,您不需要squeel。我們說「爲空」,因爲這是找到nil值的正確的SQL語法,而不是「== nil」。

+0

不幸的是,這似乎並沒有工作。 'Post Load(0.1ms)選擇「posts」。* FROM「posts」WHERE「posts」。「forum_id」= 1'仍然是控制檯中的內容,所有帖子都將通過,級別的。 – DVG 2012-04-02 11:52:23

+0

嘗試在rails控制檯本身輸入語句。你錯過了添加where子句的方式。 – 2012-04-02 16:56:02

+0

是的,事實證明我是在視圖層中搞亂了它 – DVG 2012-04-03 21:26:34

相關問題