ActiveRecord has_many :through where status = 'pending'

ActiveRecord has_many :through where status = 'pending'

我想增强处于待定状态的用户关注度:

class Relationship < ActiveRecord::Base
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
end

class User < ActiveRecord::Base
  has_many :active_relationships, class_name:  "Relationship",
                                  foreign_key: "follower_id",
                                  dependent:   :destroy
  has_many :following, through: :active_relationships, source: :followed
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
  has_many :followers, through: :passive_relationships, source: :follower
end

所以,我为状态字段添加了一个迁移

rails g migration AddStatusToRelationships

class AddStatusToRelationships < ActiveRecord::Migration
  def change
    add_column :relationships, :status, :string
  end
end

关系table现在看起来像

id | follower_id | followed_id | status

目标是显示状态关系:"pending"

我的增强方法

has_many :followers, through: :passive_relationships, source: :follower

类似

has_many :followers, -> { where status: "pending" }, through:
               :passive_relationships, source: :follower

给我

SQLite3::SQLException: no such column: users.status: SELECT COUNT(*) 
FROM "users" INNER JOIN "relationships" 
ON "users"."id" = "relationships"."follower_id" 
WHERE "relationships"."followed_id" = ? 
AND "users"."status" = 'pending'

所以我尝试了

has_many :followers, through: :passive_relationships -> { 
               where status: "pending" }, source: :follower

哪个returns

SyntaxError in UsersController#show app/models/user.rb:20: 
syntax error, unexpected ->, expecting keyword_end ...ough:
:passive_relationships -> { where status: "pending" },
... ... ^ app/models/user.rb:20: 
syntax error, unexpected ',', expecting keyword_end ...-> { 
where status: "pending" }, source: :follower ... ^

我也试过了

has_many :pending, through: :passive_relationships, 
    source: :follower, 
    :conditions => ['passive_relationships.status = ?','pending']

哪个returns

Unknown key: :conditions. Valid keys are: :class_name, :anonymous_class, 
:foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, 
:before_remove, :after_remove, :extend, :primary_key, :dependent, :as, 
:through, :source, :source_type, :inverse_of, :counter_cache, :join_table, 
:foreign_type

感谢帮助!

has_many :followers, -> { joins (:relationships).where(relationships: { status: 'pending' }) }, through: :passive_relationships, source: :follower

我会用下面的形式写它,但不确定它是否是一个有效的语法(由于 stabby lambda 条件):

has_many :followers,
  -> { joins(:relationships).where(relationships: { status: 'pending' }) },
  through: :passive_relationships,
  source: :follower