【发布时间】:2016-01-21 15:16:43
【问题描述】:
我想以待定状态增强用户关注:
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
感谢您的帮助!
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 activerecord associations has-many-through