# How to set foreignkey in such a situation?

**URL:** <https://www.ruby-forum.com/t/how-to-set-foreignkey-in-such-a-situation/57348>\
**Category:** Rails\
**Created:** [April 10, 2006, 7:00am UTC](https://www.ruby-forum.com/t/how-to-set-foreignkey-in-such-a-situation/57348 "2006-04-10T07:00:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![charlie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/d6d6ee/32.png) [@charlie](https://www.ruby-forum.com/u/charlie)\
**Post date:** [April 10, 2006, 7:00am UTC](https://www.ruby-forum.com/t/how-to-set-foreignkey-in-such-a-situation/57348/1 "2006-04-10T07:00:20Z")

</div>

Table articles has column: author,body,etc  
Table users has column: login\_name,email,etc  
articles belongs\_to user  
users has many articles

foreign\_key author references users(login\_name)

Therefore in Article.rb:

belongs\_to:article\_user,  
:class\_name=\>“User”,  
:foreign\_key=\>“author”  
and what’s going on? how the rails find the reference relationship  
between articules(author) and users(login\_name)?

---

<div class="post-metadata">

**Author:** ![charlie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/d6d6ee/32.png) [@charlie](https://www.ruby-forum.com/u/charlie)\
**Post date:** [April 10, 2006, 10:58am UTC](https://www.ruby-forum.com/t/how-to-set-foreignkey-in-such-a-situation/57348/2 "2006-04-10T10:58:53Z")

</div>

Charlie wrote:

> Table articles has column: author,body,etc  
> Table users has column: login\_name,email,etc  
> articles belongs\_to user  
> users has many articles
> 
> foreign\_key author references users(login\_name)
> 
> Therefore in Article.rb:
> 
> belongs\_to:article\_user,  
> :class\_name=\>“User”,  
> :foreign\_key=\>“author”  
> and what’s going on? how the rails find the reference relationship  
> between articules(author) and users(login\_name)?

You can use the :finder\_sql option when to define the association, to  
set what you want:

class Article \< ActiveRecord::Base  
belongs\_to :article\_user,  
:class\_name =\> “User”,  
:finder\_sql =\> “select u.\* from user u, article a where u.login\_name  
= a.author”

I believe that’ll do what you’re looking for.

Jeff C.man
