2015-05-27 37 views
0
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 

我想问一下关系。如何更正与Rails中两个模型之间的关系:foreign_key?

@ dispute.claimant.name和@ dispute.indicted.name工作良好,但我怎样才能使用反向关系,例如@ claimant.dispute.reason。我想我可以使用@indicted_disputes = Dispute.select {|x| x.indicted_id == current_user.id},但我不知道这个数据库有多快可以工作。

我尝试在dispute_controller中创建一些方法:sent_disputes(所有用户争议,其中user.id == claimant_id)和received_disputes(其中user.id == indicted_id)。 但不明白如何设置用户像索赔人?通常的方式来设置用户是@user = User.find(params [:user_id]),我想要建立类似的东西:@claimant = User.find(params [:claimant_id])和do @ claimant.disputes(其中应该是只有用户是申诉人的纠纷) 使用“索赔人关系”和加载一些数据如@ claimant.dispute.reason是另一种更“自然”的方式吗? 感谢您的帮助,谢谢。

回答

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

由于has_many关系的用户可以是申请人和被控同时多个纠纷。如果您只是想检查用户是否是申请人:

@user.disputes.where(claimant_id: @user.id).present? 
+0

我在尝试应用您的解决方案时出错。 'DEF disputes_list @disputes = current_user.disputes.where(:indicted_id == current_user.id) @disputes = @ disputes.paginate(页面:PARAMS [:页])如果@ disputes.any? end' 返回错误 SQLite3 :: SQLException:no such column:disputes.user_id:SELECT 1 AS one FROM“dispute”WHERE“dispute”。“user_id”=? LIMIT 1 – anndrew78

+0

只是一个语法错误,我想..编辑我的答案 – jpriebe

相关问题