Question

I setup Devise on User model with its default options.

I also have a Company model that needs to add data added whenever a user registers. A company owner setups a User to login with and a Company profile, both in the same form.

I setup Company model with has_many :users and User with has_one :company, but I keep getting Can't mass-assign protected when submitting the form. I followed Profile model for Devise users? and others from Stackoverflow, but no luck.

How can I setup the User and Company model to add the necessary data whenever a user registers? User data to User and company data to Company.

Was it helpful?

Solution 2

How I got it working:

My User model has:

attr_accessible :company_attributes

belongs_to :company
accepts_nested_attributes_for :company

My Company model has:

has_many :users

And the new.html.erb from devise/registrations is with the following added:

<% resource.build_company %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
[ fields for User ]
<%= f.fields_for :company_attributes, resource.company do |company| %>
[ fields for Company ]
<% end %>
<% end %>

OTHER TIPS

You can use a callback to create a object Company after create a user, for example on your User.rb model add: (I don't know your company attributes but you can take a look to this example)

after_create :first_company
 def first_company
  company = self.company.new(:title => "Company title here", :created_at => Time.now #add more attributes if required)
  board.save!
 end

You must add attr_accessible to attributes that you receive from your action controller. Add the next code on your models to remove the Can't mass-assign protected

attr_accessible :title #...more attributes if required

Regards!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top