0

我已经建立了一个基本的论坛。我希望 posts#index 操作仅显示 parent_post_id 为 nil 的记录,因此不显示回复帖子。我已经安装了squeel,但我不确定我是否设置正确。

  #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
4

1 回答 1

1

尝试

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

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

我们说“posts”而不是“post”,因为表的名称是“posts”

添加了这种简单的 where 子句不需要 squeel。我们说“is null”,因为这是查找 nil 值的正确 SQL 语法,而不是“== nil”。

于 2012-04-02T02:22:03.110 回答