I have a model, Announcement, with an enum
Audience = ['everyone', 'signed_in_only','visitor_only', 'app_only', 'exclude_app']
enum audience: Audience
The announcements controller defines audience_params
def announcement_params
params.require(:announcement).permit(:body, :audience, :expiry)
end
In creating an announcement, the audience_params are
<ActionController::Parameters {"body"=>"This is for everyone", "audience"=>"0", "expiry"=>"27/01/2018"} permitted: true>
My code in the action method of the announcements controller includes
@announcement = Announcement.new(announcement_params)
@announcement.audience = @announcement.audience.to_i
which worked with rails 5.0. But now the first line throws an exception
ArgumentError: '0' is not a valid audience
presumably because the audience value has not been converted to integer. Given the new method does not do validations, why is this error being thrown in rails 5.1 and how do I fix this?
enum
is meant to allow you to use symbolic names rather than numbers. The accessors they define expect you to give a string or symbol, rather than the underlying numeric value.
You should be using
@announcement.audience = 'everyone'
not
@announcement.audience = 0
This behavior may have changed in newer Rails, but the correct thing has always been to assign the human-readable string, not the numeric value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With