Search code examples
ruby-on-railsattributesupdate-attributes

nested model form and update_attributes


I have a nested-model form with a one-to-many relationship between a class Project and class TeamMember, and in the controller, an update function like :

@project = Project.find(params[:id])

@project.update_attributes(params[:project])        

Now, I'd like to set some fields that are not set in the form for some of the team members before the saving happens. I cannot use the update_attributes function as is to do so.

What would be the best way to do it ?

Thanks, Nicolas.


Solution

  • I would look into the accepts_nested_attributes_for function. You might have something like:

    class Project < ActiveRecord::Base
      has_one :team
      accepts_nested_attributes_for :team
    
      # also this will be useful
      validates_associated :team
    end
    

    In your forms you will want to use the fields_for method to nest your attributes. That might look something like:

    <% form_for(@project) do |p| %>
      <%= p.error_messages %>
      <!-- Project name -->
      <%= p.text_field :name %>
    
      <% f.fields_for(@project.team) do |t| %>
        <!-- Team Name -->
        <%= t.text_field :name %>
      <% end %>
    
      <%= f.submit 'Create Project' %>
    <% end %>
    

    When you submit the form you will be able to call @project.update_attributes(params[:project]) and it will work. You can also raise params.inspect to see how the params are nested.

    Hope this helps.