友谊has_many通过模型与多个状态’

目前我的用户模型具有以下代码:

has_many :notifications has_many :friendships has_many :friends, :through => :friendships, :conditions => { status: 'accepted' } has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => { status: 'requested' } has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => { status: 'pending' } 

我的友谊模型如下:

  belongs_to :user belongs_to :friend, :class_name => "User" def self.request(user, friend) unless user == friend or Friendship.exists?(user_id: user, friend_id: friend) transaction do Friendship.create(:user => user, :friend => friend, :status => 'pending') Friendship.create(:user => friend, :friend => user, :status => 'requested') end else return "failed" end end def self.accept(user, friend) unless user == friend or Friendship.exists?(user_id: user, friend_id: friend) transaction do accepted_at = Time.now accept_one_side(user, friend, accepted_at) accept_one_side(friend, user, accepted_at) end else return "failed" end end def self.accept_one_side(user, friend, accepted_at) request = find_by_user_id_and_friend_id(user, friend) request.status = 'accepted' request.accepted_at = accepted_at request.save! end 

但是,当我尝试运行我的黄瓜测试时,我收到此错误:

 SQLite3::SQLException: no such column: users.status: SELECT "users".* FROM "users" INNER JOIN "friendships" ON "users"."id" = "friendships"."friend_id" WHERE "users"."status" = 'accepted' AND "friendships"."user_id" = ? (ActionView::Template::Error) 

我认为这意味着它只是试图在内部包含例如pending_friends,具有属性status =“pending”的用户,其中它实际上应该包括属于具有属性status =“pending”的友谊的用户

这是正确的吗? 我该如何解决这个问题?

我找不到任何关于使用has_many :conditions文档,但根据生成的错误,我认为指定的条件假定适用于has_many主题模型,而不是目标模型或它正在引用的模型。

我已更新到以下内容,这有效:

  has_many :notifications has_many :friendships has_many :accepted_friendships, :class_name => "Friendship", :conditions => {status: 'accepted'} has_many :requested_friendships, :class_name => "Friendship", :conditions => {status: 'requested'} has_many :pending_friendships, :class_name => "Friendship", :conditions => {status: 'pending'} has_many :friends, :through => :accepted_friendships has_many :requested_friends, :through => :requested_friendships, :source => :friend has_many :pending_friends, :through => :pending_friendships, :source => :friend 

但是,如果有人有不同的方法而不必创建accepted_friendshis,requested_friendships和pending_friendships,我很乐意听到它!

statusfriendships表的列。

因此,当您编写代码时,请提及表名,否则它将采用Current模型的表。

 has_many :friends, -> { where "friendships.status = 'accepted'" }, :through => :friendships