How do I use nested attributes with the devise model

前端 未结 3 1586
情深已故
情深已故 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:10

    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.

    0 讨论(0)
  • 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)".

    0 讨论(0)
  • 2020-12-07 22:12

    I realised this is a very old thread, but since I found a better solution, hence the reply.

    Just change the new.html.erb as follows,

    <% form_for(resource, :as => resource_name,:url => registration_path(resource_name) do |f| %>
        ...
        <% prefix = "user[company_attributes]"%>
        <% fields_for prefix, @user.company do |company_form| %>
        ...
        <% end %>
    <% end %>
    

    This way when @user.save gets invoked, it would run company.save too with all the validations you may have in company model.

    I don't have whole lot of RoR experience, but I think this is a better solution. What do you think?

    0 讨论(0)
提交回复
热议问题