Ask A Question

Notifications

You’re not receiving notifications from this thread.

Build a Devise Model in another controller

Roman Storm asked in Gems / Libraries

Lets say we have a Company model which accepts_nested_attributes_for User (devise Model)

How do we Save both a company and User model having that a Company has_many :users and a User belongs to a Company???

Users has :confirmable option as well.

so after successful creation of those, we should have company with company_id, a user with company_id as well assigned to him.

Reply

Yo! So I think having accepts_nested_attributes_for is really the main thing for making this work. The only other thing you really need is to make sure that your strong_params in the controller accepts those attributes.

What it will do is create or update the Company with its own attributes and then accepts_nested_attributes_for will automatically create the nested models for you (the Users) and it will also associate them too.

Probably the main thing to watch out for is that you need to also make sure the nested models are validated. Devise is going to require a password for the Users (by default) so you'll possibly need to set some default passwords for those users.

Are you having trouble making this work? Also the cocoon gem is great for creating those nested forms for the nested models. https://github.com/nathanvda/cocoon

Reply

Figured it out. It was the problem that I didn't permit and sanitized params, even though they were exactly the same in order to User.new user.save

Reply

Ah! That would do it! :)

Reply

Basically I did STI on User model, and made it working and then removed whatever I did, installed rolify + pundit :-)

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.