【问题标题】:Rails associations has_manyRails 关联 has_many
【发布时间】:2014-07-15 12:40:56
【问题描述】:

我目前有一个模型:用户,我希望能够向每个用户添加 has_manyfriend_requests。我是否必须创建另一个名为模型的模型:“Friend_Request”,其中包含belongs_to:user?或者我将如何去做。我希望用户有很多friend_requests,同时也能够request_friendship。我完全迷失了,有人可以帮助我。提前谢谢你。

 Note: This is for rails 4, if that matters.

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    是的,您需要两个模型。无论何时使用has_manybelongs_to,您都需要为关系的每个部分建立一个模型。

    所以,在这里,你需要:

    class User < ActiveRecord::Base
      has_many :friend_requests
    end
    
    class FriendRequest < ActiveRecord::Base
      belongs_to :user
      belongs_to :friend
    end
    
    class Friend < ActiveRecord::Base
      has_many :friend_requests
    end
    

    然后您将需要usersfriend_requests 表。像这样:

    class CreateUsers < ActiveRecord::Migration
      def change
        create_table :users do |t|
          t.string :name
        end
      end
    end
    
    class CreateFriendRequests < ActiveRecord::Migration
      def change
        create_table :friend_requests do |t|
          t.integer :user_id
          t.integer :friend_id
        end
      end
    end
    
    
    class CreateFriends < ActiveRecord::Migration
      def change
        create_table :friends do |t|
          t.string :name
        end
      end
    end
    

    希望对您有所帮助!祝你好运!

    【讨论】:

    • 你会如何模拟谁在你的协会中请求友谊?
    • 我会为 Friend 添加一个模型,并在 FriendRequest 模型中添加belongs_to :friend。像这样:class User &lt; ActiveRecord::Base has_many :friend_requests endclass FriendRequest &lt; ActiveRecord::Base belongs_to :user belongs_to :friend endclass Friend &lt; ActiveRecord::Base has_many :friend_requests end。查看上面代码的变化!
    【解决方案2】:

    无论您使用哪个版本的 Rails,这都是关于现实模型的。我建议添加以下模型

    class CreateContactRequests < ActiveRecord::Migrations
      def change
        create_table :contact_requests do |t|
          t.references :owner
          t.references :user
          t.string :type #incoming/outcoming
        end
      end
    end
    
    class User
      has_many :freinds_requests, -> { where("contact_requests.type = 'outcoming ")}, :foreign_key => 'owner_id', :class => "ContactRequest"
      has_many :requested_freindships, -> { where("contact_requests.type = 'incoming ")}, :foreign_key => 'owner_id', :class => "ContactRequest"
    end
    
    class ContactRequest
      belongs_to :owner, :class_name => 'User'
      belongs_to :user
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多