Ognjen Regoje bio photo

Ognjen Regoje
But you can call me Oggy


I make things that run on the web (mostly).
More ABOUT me and my PROJECTS.

me@ognjen.io LinkedIn

Rails pattern: state params

#rails #technical

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.