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

时间:2013-12-24 06:19:22

标签: sql ruby-on-rails has-many-through

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

  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”的友谊的用户

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

3 个答案:

答案 0 :(得分:0)

statusfriendships表的列。

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

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

答案 1 :(得分:0)

我无法找到:conditionshas_many一起使用的任何文档,但根据生成的错误,我认为指定的条件适用于到作为has_many主题的模型,而不是目标模型或它所引用的模型through

答案 2 :(得分:0)

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

  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,我很乐意听到它!