我希望使用待处理状态增强用户跟踪功能:
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
关系表现在看起来像
id | follower_id | followed_id | status
目标是显示状态关系:“待定”
我的提升方法
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
返回
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']
返回
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
感谢您的帮助!
答案 0 :(得分:1)
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