Setup Double Foreign Keys Posted on October 21st, 2010
This is how to create a model relationship in Ruby on Rails where one model, Message, has two foreign keys to another model, User. The sql tables are defined below, and is given the solution in Ruby and how to retrieve the values.
CREATE TABLE `user`(
`id` INT(10) PRIMARY KEY,
`name` VARCHAR(25)
);
CREATE TABLE `message` (
`id` INT(10) PRIMARY KEY,
`author_user_id` INT(10),
`recipient_user_id` INT(10),
`subject` VARCHAR(250)
);
To create the correct ORM relations use the following ruby code:
class Message < ActiveRecord::Base
belongs_to :author, :class_name => "User", :foreign_key => "author_user_id"
belongs_to :recipient, :class_name => "User", :foreign_key => "recipient_user_id"
end
With the above code you can access user data via <%= @message.author.name %>