代码之家  ›  专栏  ›  技术社区  ›  Mike Sutton

需要有关Rails中SQL连接的帮助吗

  •  0
  • Mike Sutton  · 技术社区  · 15 年前

    我有一个通过User_id属于User的表Blog。

    我使用thinking sphinx为博客编制索引,但我只希望它为用户当前处于活动状态的博客编制索引(user.status=user::active)。

    define_index do
        indexes title
        indexes body
    
        where "user.status = '#{User::ACTIVE}'"
    end
    

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

    搞乱SQL似乎连接必须在WHERE之前进行,因此使用SQL代码不可能做到这一点,除非有人知道得更清楚。

    4 回复  |  直到 15 年前
        1
  •  0
  •   Jaime Bellmyer    15 年前

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

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

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

    这将自动更新您的博客状态。我不知道一个用户是否有很多博客,如果是这样的话,请相应地调整代码。

    然后使用适当的where子句更新博客索引器:

    define_index do
      indexes title
      indexes body
    
      where "status = '#{User::ACTIVE}'"
    end
    

        2
  •  1
  •   St.Woland    15 年前

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

    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
    

    manual .

        3
  •  0
  •   Jimmy Baker    15 年前

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

    users.status = '#{User::ACTIVE}'
    
        4
  •  0
  •   James Healy    15 年前

    您可能只需要一个伪属性来确保thinking sphinx连接blog和user表。在不了解模式细节的情况下,尝试以下方法:

    define_index do
        indexes title
        indexes body
        has user(:id), :as => :user_id
    
        where "users.status = '#{User::ACTIVE}'"
    end