【问题标题】:How do I define a foreign key that points to a class of a different name in ActiveRecord with Rails?如何使用 Rails 在 ActiveRecord 中定义指向不同名称的类的外键?
【发布时间】:2011-01-12 03:59:59
【问题描述】:

我有一个模型 Follow,它定义了一个 user_id 和一个 follow_user_id。如果您使用过 Twitter,这应该是有道理的。

我试图让 follow_user_id 指向一个 User 模型,所以我可以通过 f.followed_user 访问被关注的用户(就像我有一个带有 belongs_to :user 和 user_id 列的条目一样可以使用entry.user获取用户。)

我该怎么做?

谢谢!

【问题讨论】:

    标签: ruby-on-rails activerecord model


    【解决方案1】:

    查看此截屏视频
    http://railscasts.com/episodes/163-self-referential-association
    它展示了如何在 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
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      belongs_to :followed_user, :class_name => "User"
      

      【讨论】:

        【解决方案3】:

        本文将向您详细介绍如何解决此问题所需了解的内容:

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

        直接来自文章:

        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
        

        这篇文章完整地解释了什么、为什么以及如何。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-14
          • 1970-01-01
          相关资源
          最近更新 更多