Relationships with using foreign_key

Good time.
Try to solve next problem. I have two models: user and dispute. User has many disputes and dispute must contain two users (claimant with :claimant_id and indicted with :indicted_id). So instead :user_id in dispute model I have two columns with foreign_keys

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

Schema is next:

create_table “users”, force: true do |t|

t.string “name”

t.string “email”

t.datetime “created_at”

t.datetime “updated_at”

t.string “password_digest”

t.string “remember_token”

t.boolean “admin”, default: false

end

create_table “disputes”, force: true do |t|

t.integer “post_id”

t.string “reason”

t.integer “claimant_id”

t.integer “indicted_id”

t.datetime “created_at”

t.datetime “updated_at”

end

Relationships like @dispute.claimant.name or @dispute.indicted.email working pretty well. But reverse relationships are troubles and sorrows

The problem is:

In dispute_controller i create a method which find all user disputes, where user is a indicted in dispute

def disputes_list

@user = current_user

@disputes = @user.disputes.where(indicted_id: @user.id) # also used @user.disputes.where(“claimant_id = ?”, @user.id)

@disputes = @disputes.paginate(page: params[:page])

end

This method return me a headache:

ActiveRecord::StatementInvalid in Disputes#disputes_list

SQLite3::SQLException: no such column: disputes.user_id: SELECT COUNT(*) FROM "disputes" WHERE "disputes"."user_id" = ? AND "disputes"."indicted_id" = 1

How I think, when I build a call like @user.disputes ActiveRecord try to find a column with user_id in dispute model, but I have :claimant_id and :indicted_id instead :user_id

It’s my first time with using foreign_key, so I can make mistake in design. Please help me fix it. Thank you

Yes, active record assumes that the foreign key to use is user_id.If the association should use a different key then you must tell active record, e.g.

has_many :users, foreign_key: ‘claimant_id’

You could also do

has_many :claimants, class_name: ‘User’ #don’t need to set foreign key because default is inferred from the association

Fred