0

I have the following code in my controller:

login = params[:user_registration][:login]
password = params[:user_registration][:password]
email = params[:user_registration][:email]

It's too verbose and ugly, any smarter way to extract the keys I need?

2
  • Can you give some more detail on what you're trying to do? If for instance you're trying to create a new User record, typical we do the following: User.new(params[:user]). I guess in your case it would be User.new(params[:user_registration]) - not entirely sure why though. Commented Jun 18, 2013 at 18:08
  • Do you have a UserRegistration class and was the form built from it? Commented Jun 18, 2013 at 18:12

4 Answers 4

4

Perhaps this?

login, password, email = params[:user_registration].values_at :login, :password, :email
Sign up to request clarification or add additional context in comments.

2 Comments

Great, thanks! Btw, what about user.name, user.password, user.email = params[:user_registration].values_at :name, :password, :email? Any way to skip repeating user in left part of assignment?
Personally, I usually write a set_from_params method or something to that order for that kind of stuff. Within it, do something like hash.each { |key, val| __send__("#{key}=", val) }.
1

It may be worth your while encapsulating the attributes in a class, if indeed you don't already have one. Perhaps a UserRegistration class? Then you could do;

@new_user = UserRegistration.new(params[:user_registration])

This would make passing the attributes over to models and views more convenient too.

Comments

0

Package them together, and only overwrite when needed

attrs = params[:user_registriation]
attrs.email.downcase! # Only overwrite on selected attr when needed.

Comments

0

I often do it this way:

user_params = [:login, :password, :email]

User.new(params.select {|v| user_params.include?(v)})

This passes only the parameters that are necessary for creating the model and it's clear to read.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.