How do i specify and validate an enum in rails?

前端 未结 8 1850
南笙
南笙 2020-12-30 20:15

I currently have a model Attend that will have a status column, and this status column will only have a few values for it. STATUS_OPTIONS = {:yes, :no, :maybe}

1)

8条回答
  •  无人及你
    2020-12-30 20:45

    After some looking, I could not find a one-liner in model to help it happen. By now, Rails provides Enums, but not a comprehensive way to validate invalid values.

    So, I opted for a composite solution: To add a validation in the controller, before setting the strong_params, and then by checking against the model.

    So, in the model, I will create an attribute and a custom validation:

    attend.rb

    enum :status => { your set of values }
    attr_accessor :invalid_status
    
    validate :valid_status
    #...
    private
        def valid_status
            if self.invalid_status == true
                errors.add(:status, "is not valid")
            end
        end
    

    Also, I will do a check against the parameters for invalid input and send the result (if necessary) to the model, so an error will be added to the object, thus making it invalid

    attends_controller.rb

    private
        def attend_params
            #modify strong_params to include the additional check
            if params[:attend][:status].in?(Attend.statuses.keys << nil) # to also allow nil input
                # Leave this as it was before the check
                params.require(:attend).permit(....) 
            else
                params[:attend][:invalid_status] = true
                # remove the 'status' attribute to avoid the exception and
                # inject the attribute to the params to force invalid instance
                params.require(:attend).permit(...., :invalid_status)
           end
        end
    

提交回复
热议问题