How do I define a foreign key that points to a class of a different name in ActiveRecord with Rails?

I have a model Follow that defines a user_id and a followed_user_id. If you've used Twitter, this should make sense.

I'm trying to make followed_user_id point to a User model, so I can access the user that is being followed through f.followed_user (in the same way that if I have an Entry with belongs_to :user and a user_id column I can use entry.user to get the user.)

How can I do this?

Thanks!

--------------Solutions-------------

Check this screencast
http://railscasts.com/episodes/163-self-referential-association
It shows how a self referential association (what you are referring here) should be implemented in Rails.


# models/user.rb
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user

# friendships_controller.rb
def create
@friendship = current_user.friendships.build(:friend_id => params[:friend_id])
if @friendship.save
flash[:notice] = "Added friend."
redirect_to root_url
else
flash[:error] = "Unable to add friend."
redirect_to root_url
end
end

def destroy
@friendship = current_user.friendships.find(params[:id])
@friendship.destroy
flash[:notice] = "Removed friendship."
redirect_to current_user
end

You can do it like this:

belongs_to :followed_user, :class_name => "User"

This article walks you through exactly what you need to know on how to solve this issue:

http://www.spacevatican.org/2008/5/6/creating-multiple-associations-with-the-same-table

Straight from the article:

class Sale < ActiveRecord::Base
belongs_to :buyer, :class_name => 'User', :foreign_key => 'buyer_id'
belongs_to :seller, :class_name => 'User', :foreign_key => 'seller_id'
end

class User < ActiveRecord::Base
has_many :purchases, :class_name => 'Sale', :foreign_key => 'buyer_id'
has_many :sales, :class_name => 'Sale', :foreign_key => 'seller_id'
end

The article explains in full what, why and how.

Category:ruby on rails Time:2011-01-12 Views:1

Related post

  • Defining Multiple Foreign Keys in Visual Studio 2009-02-04

    I have a basic database schema as follows (dumbed down so it's easy to read): [Staff] StaffId (pk) FirstName LastName [RosterEvent] EventId (pk) StartDate EndDate [StaffEvents] StaffId (pk) EventId (pk) Ok so, many Staff can have many RosterEvents, w

  • How can I define a foreign key using netbeans 6.7? 2009-08-01

    I'm using JPA in netbeans with mysql and I need to define a foreign key. I want to do it graphically because it is very easy to create tables using netbeans 6.7 UI without dealing with SQL commands. Can you tell me how to do it?? --------------Soluti

  • what are the advantages of defining a foreign key 2012-04-16

    Might be a silly question, but here it goes. What is the advantage of defining a foreign key? I'm using SQL Server and cfwheels, a rails-like framework in coldfusion. Because the foreign keys are inferred from the naming structure, it seems like they

  • how to define two foreign keys in cakePHP 2010-07-02

    I got a table with a few columns. The table has a primary key (replyid), and two foreigne keys (userid and postid). Here is the structure of the table: {replyid, content, userid, postid} The Reply table got two foreigne keys. I am not sure if this is

  • Defining multiple foreign keys in one table to many tables 2010-10-29

    I have 3 models: Post: id title body Photo: id filepath Comment: id post_id body and corresponding tables in DB. Now, if I want to have comments only for my posts I can simply add following foreign key: ALTER TABLE comment ADD FOREIGN KEY (post_id) R

  • How do I define a foreign key programatically? 2011-01-06

    Ruby 1.8.7-p249, Rails 2.3.8, SQLite3. I'd like to create 2 tables programatically and define parent-child relationship between them. The foreign_key method does work in db migrations but it doesn't work in my code in ActiveRecord::Schema.define bloc

  • ASP.NET Membership Provider: Defining a foreign key to aspnet_Users.UserName 2011-11-01

    I'd like to setup a foreign key to a default membership table but I'm getting an error when trying to define it. I'm using the default aspnet_Users table and also my own Posts table. I'm trying to setup the tables as follows: aspnet_Users UserId (PK)

  • Symfony 1.4 Propel: I defined, but foreign keys isn't defined in tables 2012-01-15

    Lets see this schema: orders: _attributes: { phpName: Orders, default_table_charset: utf8, default_table_collate: utf8_general_ci } id: ~ category_id: { type: integer, size: '10', required: true, defaultvalue: '0', foreigntable: categories, foreignre

  • How to define a foreign key in Mnesia 2009-07-27

    Is there an equivalent to this SQL statement in Mnesia? alter table TABLE add foreign key (FIELD) references TABLE2 (FIELD2) --------------Solutions------------- No, you have to do all these things yourself in your mnesia transactions. Consistency is

  • Why do Rails migrations define foreign keys in the application but not in the database? 2009-05-29

    If I define a Customer and Order model in which a Customer "has many" Orders and the Order "belongs to" the Customer, in Rails we talk about Order having a foreign key to the Customer through customer_id but we don't mean that this is enforced in the

  • ROR 3 defining foreign key relationship 2011-05-09

    I'm having trouble finding a good tutorial on how to define basic foreign key relationships between models. suppose I have a User model and a Game model.. I would like to define two fields in the Game model - host_id and visitor_id which are mapped v

  • Foreign key from one app into another in Django 2008-11-27

    I'm wondering if it's possible to define a foreign key in a models.py file in Django that is a reference to a table in another app? In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things): class Movi

  • django model with two generic (content_type) foreign keys? 2009-05-28

    I'm trying to create a mapping table between two generic (content_type) references, one for "agents" and one for "resources". So I take the usual way I make a generic foreign key : content_type = models.ForeignKey(ContentType) object_id = models.Posi

  • Why can you not have a foreign key in a polymorphic association? 2009-05-28

    Why can you not have a foreign key in a polymorphic association, such as the one represented below as a Rails model? class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true end class Article < ActiveRecord::Base has_

  • Any example of a necessary nullable foreign key? 2009-05-29

    Customers customer_id Orders order_id customer_id fk If I have two tables and define a foreign key on customer_id in the Orders table, by allowing it to be null I am saying that I can have an order that does not have a customer associated with it. As

  • Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails 2009-08-10

    I'm having a bit of a strange problem, I'm trying to add a foreign key to one table that references another, but it is failing for some reason. With my limited knowledge of MySQL, the only thing that could possibly be suspect is that there is a forei

  • Why are foreign keys more used in theory than in practice? 2009-12-09

    When you study relational theory foreign keys are, of course, mandatory. But in practice, in every place I worked, table products and joins are always done by specifying the keys explicitly in the query, instead of relying on foreign keys in the DBMS

  • Why is it still possible to insert a foreign key that doesn't exist? 2010-02-23

    mysql> create table products(id integer unsigned auto_increment primary key); Query OK, 0 rows affected (0.05 sec) mysql> CREATE TABLE orders ( -> id integer PRIMARY KEY auto_increment, -> product_id integer REFERENCES products (id), -

  • Does introducing foreign keys to MySQL reduce performance 2010-04-11

    I'm building Ruby on Rails 2.3.5 app. By default, Ruby on Rails doesn't provide foreign key contraints so I have to do it manually. I was wondering if introducing foreign keys reduces query performance on the database side enough to make it not worth

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.939 (s). 13 q(s)