How do I use nested attributes with the devise model

前端 未结 3 1589
情深已故
情深已故 2020-12-07 21:35

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

3条回答
  •  轮回少年
    2020-12-07 22:11

    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)".

提交回复
热议问题