For a Rails project I'm working on, most of the information in a user's model is meant to be confidential, such as a two factor auth phone number.

I've only whitelisted the basics in the model, email, password, and password_confirmation.

I'm trying to figure out how to set up a sign-up form for this sort of User, when only a few attributes are able to be set via mass assignment. Is there some way to specify a normal set of attr_accessible properties, and a second set that are only accessible when creating a new User instance?

有帮助吗?

解决方案

I don't see what the problem is. In whatever controller action your form posts the form data to, just directly set non-whitelisted values of your model from values in params:

def create
  user = User.new(params[:user]) 
  user.phone_number = params[:user][:phone_number]
  ... <other non-whitelisted attribute assignments> ...
  user.save!
end

That will work even if phone_number is not in the list of whitelisted attributes (i.e. even if it does not appear in the arguments to attr_accessible in the User model). You can do the same for any other non-whitelisted form attributes.

其他提示

attr_accessible is on the class, so you can always re-open the class and define it again:

class User
    attr_accessible :email, :password, :password_confirmation
end

That would go in whichever controller method you want. When you're done, you can re-open the class again and set a new attr_accessible.

That's horrible, though. Instead you should look at the definition of attr_accessible and try to do what it does directly. Maybe.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top