Mysql2 ::错误:未知栏' friendship.status'在' where子句'

时间:2015-09-25 22:07:47

标签: ruby-on-rails

ArgumentError: Unknown key: :conditions. Valid keys are: :class_name, :class, :foreign_key

首先,有一个问题,几乎与我的问题类似,但我无法使其适用于我的代码。所以,我决定分开询问。

这是我收到错误的地方:

  has_many :friendships
  has_many :friends,
           :through => :friendships,
           :conditions => "status = 'accepted'",
           :order => :screen_name
  has_many :requested_friends,
           :through => :friendships,
           :source => :friend,
           :conditions => "status = 'requested'",
           :order => :created_at
  has_many :pending_friends,
           :through => :friendships,
           :source => :friend,
           :conditions => "status = 'pending'",
           :order => :created_at

我不知道是否应该分享其他一些代码来帮助您理解。如果你需要其他部分,我也可以粘贴它们。

这是完整的错误:

Unknown key: :conditions. Valid keys are: :class_name, :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 :friendships
  has_many :friends, -> { where(friendship: {status: 'accepted'}).order('created_at') }, :through => :friendships
  has_many :requested_friends, -> { where(friendship: {status: 'requested'}).order('created_at') }, :through => :friendships, :source => :friend
  has_many :pending_friends, -> { where(friendship: {status: 'pending'}).order('created_at') }, :through => :friendships, :source => :friend

这是我现在得到的错误:

Mysql2::Error: Unknown column 'friendship.status' in 'where clause': SELECT 1 AS one FROM `users` INNER JOIN `friendships` ON `users`.`id` = `friendships`.`friend_id` WHERE `friendships`.`user_id` = 6 AND `friendship`.`status` = 'requested' AND `users`.`id` = 8 LIMIT 1

这是发生错误的地方:

  def accept # accept_request
    if @user.requested_friends.include?(@friend)
      Friendship.accept_request(@user, @friend)
    end
    redirect_to profile_path(params[:id])
  end

具体来说:

if @user.requested_friends.include?(@friend)

accept_request:

  def self.accept_request(user, friend)
    transaction do
      accept_one_side(user, friend)
      accept_one_side(friend, user)
    end
  end

accept_one_side:

  private
  def self.accept_one_side(user, friend)
    request = find_by_user_id_and_friend_id(user, friend)
    request.status = 'accepted'
    request.save!
  end

1 个答案:

答案 0 :(得分:0)

问题已修复

问题在于has_many。

这是正确的版本:

  has_many :friendships
  has_many :friends, -> { where(friendships: {status: 'accepted'}).order('created_at') }, :through => :friendships
  has_many :requested_friends, -> { where(friendships: {status: 'requested'}).order('created_at') }, :through => :friendships, :source => :friend
  has_many :pending_friends, -> { where(friendships: {status: 'pending'}).order('created_at') }, :through => :friendships, :source => :friend

它可能看起来像上面的相同代码但不是。

因为在第一段代码中,我写道:"其中(友谊:"但它应该是:"其中(友谊:"所以,我忘了放' ; S'