zoonoo
zoonoo

Reputation: 525

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

Currently, I have two classes Theme and Offer mapped by a join table themes_offers containing theme_id and offer_id.

I need to implement a view with custom order of offers for each theme.

So the current idea I have is to add a column on the table, and create new activerecord class mapped to the table:

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

Would there be a better approach? The problem I have with this solution is that it will be difficult to implement activeadmin interface to handle the orders.

Upvotes: 1

Views: 222

Answers (1)

moveson
moveson

Reputation: 5213

A Rails has_and_belongs_to_many relationship is designed to create the relationship by means of a table that has two columns only: an id for each table and nothing else, not even an id of its own. See the docs here.

I think what you want is a has_many :through relationship, which will allow you to have a themes_offers table with additional attributes on it. Docs are here.

Upvotes: 2

Related Questions