2017-08-30 40 views
1

目前,我有两个类别ThemeOffer通过包含theme_idoffer_id的连接表themes_offers映射。Rails ActiveRecord:如何为has_and_belongs_to_many关系连接表提供自定义订单?

我需要为每个主题提供自定义的优惠顺序。

所以目前的想法,我已经是在表上添加一列,并创建映射到表的新ActiveRecord类:

class AddOrderToThemesOffers < ActiveRecord::Migration[5.0] 
    def up 
    add_column :themes_offers, :order, :integer 

    # mark order for each existing orders 

    add_index :themes_offers, [:theme_id, :order], unique: true, name: 'index_offer_order_on_theme' 
    end 

    def down 
    remove_index :themes_offers, 'index_offer_order_on_theme' 
    remove_column :themes_offers, :order, :integer 
    end 
end 

会不会有更好的办法?我在这个解决方案中遇到的问题是,实现activeadmin接口来处理订单将会很困难。

回答

2

A Rails has_and_belongs_to_many关系旨在通过仅具有两列的表创建关系:每个表的id并且不包含任何其他值,甚至不包含它自己的id。请参阅文档here

我想你想要的是一个has_many :through关系,这将允许你有一个themes_offers表,其上的附加属性。文档是here

相关问题