0

I need to limit my rich many-to-many association table to only one association per unique par. (rails).

That means i want terminals (model 1) and subscriptions (model 2) to have one custom_price (rich join) not any more than that.

How is this done most elegantly?

So far i have done:

  def new_custom_price
    @terminal_id = params[:terminal_id]
    @subscription_id = params[:subscription_id]

    @custom_price = CustomPrice.find_or_initialize_by_terminal_id_and_subscription_id( @terminal_id, @subscription_id)

    render action: 'custom_price'

  end

  def create_custom_price
    @terminal_id = params[:terminal_id]
    @subscription_id = params[:subscription_id]

    @custom_price = CustomPrice.new(custom_price_params.merge( :terminal_id => @terminal_id, :subscription_id => @subscription_id))

    respond_to do |format|
      if @custom_price.save
        format.js { render action: 'add_custom_price' }
      else
        format.js {  }
      end
    end

  end
usha
  • 28,973
  • 5
  • 72
  • 93
Ole Henrik Skogstrøm
  • 6,353
  • 10
  • 57
  • 89
  • This wont be a many-to-many relationship if you can only have one relation in the join table. Are you sure that's what you want? – Jon Jan 09 '14 at 18:46
  • Hmm i thought about that my self. the problem is that each Terminal can have many prices and subscriptions can have many prices. But each pari (terminal_id = 1 and subscription_id = 1) can only have one record. So could i use has_one custom_prices model in terminals/subscriptions? – Ole Henrik Skogstrøm Jan 09 '14 at 18:50
  • By definition, each pair will have only one record in the join model. Why not make the join model the CustomPrice model, with belongs_to associations to both Terminal and Subscription. No need to do anything out of the ordinary here. – Jon Jan 09 '14 at 20:54

1 Answers1

3

Two things you can do to handle this: (This is assuming "price" is the unique part of the many to many relationships)

1) Validation in CustomPrice

validates :price, uniqueness: {scope: [:terminal_id, :subscription_id]}

2) Use helpers

CustomPrice.find_or_create_by(custom_price_params.merge( :terminal_id => @terminal_id, :subscription_id => @subscription_id))
omarvelous
  • 2,774
  • 14
  • 18