Forum: Ruby on Rails How to set foreignkey in such a situation?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2cf7af8ebb619eeb30178dd8855245b8?d=identicon&s=25 Charlie (Guest)
on 2006-04-10 07:00
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)?
59ea1b450935b9d70abfec4186b7a4d5?d=identicon&s=25 Jeff Coleman (progressions)
on 2006-04-10 10:58
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 Coleman
This topic is locked and can not be replied to.