1

Let's say I have a User Model with a class method create_with_info. Currently if I want to password the params into the method using keyword parameters, It will be something like this.

# user_controller.rb

def create_with_info
  User.create_with_info(**user_info_params)
end

private
def user_info_params
  params.require([:name, :age, :email])
  params.permit(:name, :age, :email).to_h.symbolize_keys
end

# user.rb

def self.create_with_info(name:, age:, email:)
  # do something
end

I'm not sure is it the correct way to use keyword parameters in controller or is there a better way to handle? using to_h.symbolize_keys is annoying for me.

jameslee
  • 23
  • 3
  • why do you want to symbolize_keys? you can use `params.require(:user).permit(:name, :age, :email)` in user_info_params. Then `User.create_with_info(user_info_params)` and retrieve values in `self.create_with_info(user_info_params)` – Gagan Gupta Mar 17 '21 at 06:29
  • This is the way we used before. But using this way you can only see what params will come inside at the controller method `user_info_params`. And user_info_params will be a hash which you can not restrict it if you call this method in the console. – jameslee Mar 17 '21 at 12:20
  • by using permit, you're already restricting the use of 3 parameters – Gagan Gupta Mar 17 '21 at 15:31
  • Indeed. From the controller level it's safe enough. But what if I have to manually use this method in the model level? I mean, sure you can know what params you need from the controller, but if I have multiple place will use this method and some of the params is optional, then it will be hard for me to check everything. That's why I want to restrict the params in side the method definition. – jameslee Mar 19 '21 at 06:43

0 Answers0