Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use nested attributes with the devise model

I have the same issue as Creating an additional related model with Devise (which has no answer).

I have overridden the devise view for creating a new user and added a company name, I have changed the model to use accepts_nested_attributes_for

There are no errors, but it is not adding the nested record and I don't have a controller where I can modify the request.

I have the following (shortened to make it readable):

routes.rb

map.devise_for :users
map.resources :users, :has_many => :companies

user.rb

has_many :companies
accepts_nested_attributes_for :companies
devise :registerable ... etc

company.rb

belongs_to :user

new.html.erb

...
<% form_for resource_name, resource, :url => registration_path(resource_name) do |f| %>
...
  <% f.fields_for :company do |company_form| %>
    <p><%= company_form.label :name %></p>
    <p><%= company_form.text_field :name %></p>
  <% end %>
...

UPDATE: I didn't add :company to the attr_accessible list in the User model.

like image 839
Craig McGuff Avatar asked Aug 23 '10 01:08

Craig McGuff


People also ask

What are nested attributes?

Nested attributes are a way of applying sub-categories to your attributes. For instance, instead of having a single searchable attribute price , you may set up some sub-categories: price.net , price. gross , price. margin (note the use of 'dot notation' here to separate the parent attribute from its child).

What is nested attributes Rails?

Nested Attributes is a feature that allows you to save attributes of a record through its associated parent. In this example we'll consider the following scenario: We're making an online store with lots of products. Each Product can have zero or more Variants.


2 Answers

You can add the following method to the User model:

user.rb

def with_company
  self.companies.build
  self
end

And modify the view:

new.html.erb

...
<% form_for [resource_name, resource.with_company], :url => registration_path(resource_name) do |f| %>
...
  <% f.fields_for :company do |company_form| %>
  ...
  <% end %>

This way, you'll have the nested form to add one company to the user. To dynamically add multiple companies to the user, check the Railcast #197 by Ryan Bates. Make sure you are passing the pair of resources as an array, otherwide you will get an error like this: "wrong number of arguments (3 for 2)".

like image 104
Ivan Prasol Avatar answered Oct 17 '22 02:10

Ivan Prasol


You may be trying to mass assign some protected variable, OR you might not be saving a valid record. Check to make sure that the record is actually saving to the db.

like image 39
Preston Marshall Avatar answered Oct 17 '22 01:10

Preston Marshall