Rails ActiveRecord:如何为 has_and_belongs_to_many 关系连接 table 提供自定义订单?

Rails ActiveRecord : How can I give custom order for has_and_belongs_to_many relationship join table?

目前,我有两个 classes ThemeOffer 由包含 theme_id 和 [= 的连接 table themes_offers 映射18=].

我需要为每个主题实现一个具有自定义优惠顺序的视图。

所以我目前的想法是在 table 上添加一列,并创建映射到 table:

的新活动记录 class
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 接口来处理订单。

Rails has_and_belongs_to_many 关系旨在通过只有两列的 table 创建关系:每个 table 的 id,没有其他,甚至没有它自己的 id。请参阅文档 here

我想你想要的是一个 has_many :through 关系,它可以让你拥有一个 themes_offers table 和附加属性。文档是 here.