0

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.

Community
  • 1
  • 1
Max
  • 841
  • 1
  • 12
  • 25

2 Answers2

0

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!

hyperrjas
  • 10,666
  • 25
  • 99
  • 198
  • i like this solution because it doesn't involve the view, nor does it require overriding the devise controller. however, i haven't seen this answer around to solve this sort of problem. is there a down side to doing it this way? – AdamT Feb 24 '13 at 23:46
  • also, what does `board.save!` do? is that supposed to be `company.save!`? – AdamT Feb 24 '13 at 23:54
0

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 %>
Max
  • 841
  • 1
  • 12
  • 25