Home > database >  Is it possible to pass a nested property of a hash to function in ruby
Is it possible to pass a nested property of a hash to function in ruby

Time:04-27

I have this function in rails controller:

def validate_params(*props)
    props.each do |prop|
      unless params[prop].start_with?('abc')
        # return error
      end
    end
  end

im thinking if I have params[:name] and params[:bio] and I want to validate name & bio with this function (not every attribute I might want to validate), I will call it with validate_params(:name, :bio). But, for nested param it won't work like params[:user][:name]. Is there anything I can do to pass this nested property to my function or is there a completely different approach? Thanks

CodePudding user response:

Rails Validations generally belong in the model. You should post some additional info about what you're trying to do. For example, if you wanted to run the validation in the controller because these validations should only run in a certain context (i.e., only when this resource is interacted with from this specific endpoint), use on: to define custom contexts.

If you don't want to do things the rails way (which you should, imo), then don't call params in the method body. i.e.

def validate_params(*args)
  args.each do |arg|
    unless arg.start_with?('abc')
      # return error
    end
  end
end

and call with validate_params(params[:user], params[:user][:name]

but yeah... just do it the rails way, you'll thank yourself later.

  • Related