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.
Get in touch
Tell me what you thought of this post: me@ognjen.io
Or send me feedback. It will take less than 20 seconds.
Or send me feedback. It will take less than 20 seconds.