【问题标题】:Same Model for Two belongs_to Associations migration两个 belongs_to 关联迁移的相同模型
【发布时间】:2016-04-14 08:25:41
【问题描述】:

如何为具有两个对同一模型的引用的模型创建迁移。

我有一个包含两个角色的用户模型,买家和卖家,我还有一个销售模型,所以每次销售都应该有一个买家和一个卖家。

我看到 this answer 表明我的销售模式应该是这样的

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

但我不知道如何创建迁移并让它工作......!

【问题讨论】:

  • 您使用哪个数据库引擎?

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


【解决方案1】:

这称为self join,可以按如下方式创建:

#app/models/sale.rb
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

--

$ rails g migration CreateSales

#db/migrate/create_sales______________.rb
class CreateSales < ActiveRecord::Migrate
    def change
        change_table :sales do |t|
           t.references :seller
           t.references :buyer
        end
    end
end

$ rake db:migrate

【讨论】:

    【解决方案2】:

    您必须创建以下迁移:

    rails g migration AddBuyerAndSellerToSales buyer:references seller:references
    

    这应该会创建以下迁移文件:

    class AddBuyerAndSellerToSales < ActiveRecord::Migration
      def change
        add_reference :sales, :buyer, index: true, foreign_key: true
        add_reference :sales, :seller, index: true, foreign_key: true
      end
    end
    

    如果您使用像 PostgreSQL 这样的数据库引擎,您必须告诉引擎外键将指向哪个表。

    class AddBuyerAndSellerToSales < ActiveRecord::Migration
      def change
        add_reference :sales, :buyer, index: true   # foreign_key: true <= remove this!
        add_reference :sales, :seller, index: true  # foreign_key: true <= remove this!
    
        add_foreign_key :sales, :users, column: :buyer_id
        add_foreign_key :sales, :users, column: :seller_id
      end
    end
    

    希望这会有所帮助!

    【讨论】:

    • 看起来不错,谢谢,我可以致电 Buyer.sales 或 Seller.sales 吗?
    • 否,因为您没有 BuyerSeller 模型。如果您有这些模型,则必须将此表的外键添加到 sales 表中,然后创建 one-to-many 关系。你有BuyerSeller 型号吗?
    • 没有模型,我无法让@user.sales 工作,它给出了错误 ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column sales.user_id does not exist
    • 运行rails g migration AddUserToSales user:references 并迁移它。那么它应该可以工作了。
    • 但我不是已经在销售表上作为买家和卖家拥有这些列了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多