在模型中使用与foreign_key的关系时Rails中的SQLException

时间:2015-05-27 18:13:45

标签: ruby-on-rails relationship foreign-key-relationship

class User 
   has_many :disputes
end

class Dispute
    belongs_to :claimant, class_name: 'User', :foreign_key => :claimant_id
    belongs_to :indicted, class_name: 'User', :foreign_key => :indicted_id
end

@ dispute.claimant.name和@ dispute.indicted.name工作正常。 但是当我尝试

@user.disputes.where (claimant_id == @user.id)
@user.disputes.where (indicted_id == @user.id)

我收到一个错误:SQLite3 :: SQLException:没有这样的列:disputes.user_id:SELECT 1 AS一个FROM“争议”WHERE“争议”。“user_id”=?限制1 怎么了?怎么解决? 谢谢你的帮助

2 个答案:

答案 0 :(得分:0)

好像你在where中使用了无效的语法:

@user.disputes.where(claimant_id: @user.id)
@user.disputes.where(indicted_id: @user.id)

您正在传递布尔值但是应该传递带有SQL查询条件的哈希。

答案 1 :(得分:0)

我认为更改协会将解决您的问题。

class User < ActiveRecord::Base
  has_many :claimant_disputes, class_name: 'Dispute', foreign_key: "claimant_id"
  has_many :indicted_disputes, class_name: 'Dispute', foreign_key: "indicted_id"
end

class Dispute < ActiveRecord::Base
  belongs_to :user
end

现在在控制台尝试这样。

2.1.0 :019 > u = User.first
  User Load (0.2ms)  SELECT  `users`.* FROM `users`  ORDER BY `users`.`id` ASC LIMIT 1
 => #<User id: 1, name: "a", created_at: "2015-05-28 10:48:05", updated_at: "2015-05-28 10:48:05"> 
2.1.0 :020 > u.claimant_disputes
  Dispute Load (0.5ms)  SELECT `disputes`.* FROM `disputes` WHERE `disputes`.`claimant_id` = 1
 => #<ActiveRecord::Associations::CollectionProxy [#<Dispute id: 1, name: "test", claimant_id: 1, indicted_id: nil, created_at: "2015-05-28 10:48:47", updated_at: "2015-05-28 10:48:47">]>

2.1.0 :025 > u = User.last
  User Load (0.3ms)  SELECT  `users`.* FROM `users`  ORDER BY `users`.`id` DESC LIMIT 1
 => #<User id: 2, name: "b", created_at: "2015-05-28 10:48:08", updated_at: "2015-05-28 10:48:08"> 
2.1.0 :026 > u.indicted_disputes
  Dispute Load (0.5ms)  SELECT `disputes`.* FROM `disputes` WHERE `disputes`.`indicted_id` = 2
 => #<ActiveRecord::Associations::CollectionProxy [#<Dispute id: 2, name: "test1", claimant_id: nil, indicted_id: 2, created_at: "2015-05-28 10:48:54", updated_at: "2015-05-28 10:58:59">]>