Ognjen Regoje bio photo

MY NAME IS
Ognjen Regoje
BUT YOU CAN CALL ME OGGY


I make things that run on the web (mostly).
More /ABOUT me.

me@ognjen.io Twitter LinkedIn Github

Rails pattern: state params

A useful pattern that I didn’t see documented before is what I call “state params”: returning different permitted params based on the state of the record.

If there is an order model, the simplest way of returning permitted params is like this:

def order_params
  params.require(:order).permit(:coupon, :rating)
end

However, that means that technically rating could be submitted before the order is paid, for instance.

The application is more secure if permitted params takes into consideration the state of the order and accepts only the fields for that state.

def order_params(order)
  case order.status
  when "pending_payment"
    params.require(:order).permit(:coupon)
  when "paid"
    params.require(:order).permit(:rating)
  when "rated"
    nil
  end
end

That way coupon will be accepted only when pending payment, rating only when paid and otherwise nothing.

#rails #technical