0

我有一个表博客通过 user_id 属于用户。

我正在使用thinking sphinx 来索引博客,但我只希望它索引用户当前处于活动状态的博客(user.status = User::ACTIVE)。

我有以下用于创建索引的代码,但我知道“where”子句是错误的。应该是什么?

define_index do
    indexes title
    indexes body

    where "user.status = '#{User::ACTIVE}'"
end

更新:据我所知, where 方法只是将 SQL 代码传递给数据库引擎。看起来这应该可以通过传入 JOIN 的代码来实现,但我不知道有什么足够的 SQL 来自己创建一个 JOIN 语句。

第二次更新:使用 SQL 似乎 JOIn 必须在 WHERE 之前进行,因此使用 SQL 代码是不可能的,除非有人知道得更好。

4

4 回答 4

1

也许你应该试试users(表名是复数)

define_index do
    indexes title
    indexes body

    # Use this line, if status is numeric
    where "users.status = #{User::ACTIVE}"

    # ... and this one, if it's a string
    where "users.status = '#{User::ACTIVE}'"
end

毕竟,您可能想看看手册

于 2010-01-16T23:41:53.673 回答
0

我对狮身人面像了解不多,但只是在黑暗中尝试..

users.status = '#{User::ACTIVE}'
于 2010-01-16T23:13:34.773 回答
0

您可能只需要一个虚拟属性来确保思考 sphinx 加入博客和用户表。在不知道架构细节的情况下,尝试以下操作:

define_index do
    indexes title
    indexes body
    has user(:id), :as => :user_id

    where "users.status = '#{User::ACTIVE}'"
end
于 2010-01-17T00:46:31.077 回答
0

我不相信该where条款支持这一点。它在幕后添加到 SQL,但它无法访问 Rails 关联。另一种方法是给你的博客记录一个状态字段,这取决于用户。

首先,在您的博客表中添加一个状态字段。然后,将其添加到您的用户模型中:

before_save :update_blog_status

protected

def update_blog_status
  self.blog.update_attribute(:status, self.status)
end

这将自动更新您的博客状态。我不知道一个用户是否拥有多个博客,所以如果是这种情况,只需相应地调整此代码。

Then update your blog indexer with the appropriate where clause:

define_index do
  indexes title
  indexes body

  where "status = '#{User::ACTIVE}'"
end

That should be all you need :)

于 2010-01-17T03:18:43.740 回答