2017-08-30 44 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

相關問題