开发者

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 m开发者_如何学Goake 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜