How can I set the value to the nested column when

2019-09-06 16:39发布

问题:

User model has one user_profile.
I just installed devise and its working fine.

I made registrations_controller.rb and it has 'create', 'after_update_path_for(resource) ', and 'edit' actions.

If I want to make it input '45' to nested column of user_profile as default value, how can I code in registration controller???

Should I make another action called 'save/or new?' , and write this?

@user.user_profile.language_id = '45'

回答1:

I was making some tests, and I suggest you to use callbacks, but you can also override the actions of the RegistrationsController of Devise. I followed this thread: Override devise registrations controller and the code of the controller https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb (see that I use sign_in instead of sign_up - I'm working with Rails 3.2.8)

And this is the code with the edits for the case:

class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end

  def create
    build_resource

    resource.build_user_profile
    resource.user_profile.language_id = 45

    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_in(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

  def update
    super
  end
end 

And as the answer of the post said, I leave the routes as follows:

devise_for :users, :controllers => {:registrations => "registrations"}

I used a has_one relationship.