0

as title, I have product & order model with nested relationship, like:

resources :products do
  resources :orders 
end

Products has a filed, it name is 'amount', for example is 5.

how can I limit orders total counts less than or equal to 5?

I don't know how to use parent keyword in order model. Who can help me? thanks.

I need a resolution, thanks.

1 Answer 1

0

We can act in this way. Here, I'll give you an answer in the form of a piece of code. You can test the code below, where I've created a method to handle this limit.

class Order < ApplicationRecord
  # association
  belongs_to :product
  # create callback
  before_create :check_order_limit

  private

  # created method which is called before creation
  def check_order_limit
    errors.add(:base, 'Oops, Limit Exceeded!') if product.orders.size >= product.amount
  end
end
Sign up to request clarification or add additional context in comments.

1 Comment

I try but it's not work! github.com/afgnsu/limit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.