Mike
Mike

Reputation: 1361

how to update multiple models with rails form

I have following two models

class Office < ActiveRecord::Base
    has_many :locations, :dependent => :destroy
end

class Location < ActiveRecord::Base
    belongs_to :office
end

I have a new.html.erb for the office model and the below code in OfficeController

  def create
    @office = Office.new(params[:deal])
    if @office.save
      redirect_to office_url, :notice => "Successfully created office."
    else
      render :action => 'new'
    end
  end

How can I add fields for Location model in new.html.erb of Office?

I want to be able to have fields for locations in the same form.

Upvotes: 4

Views: 235

Answers (1)

Logan Leger
Logan Leger

Reputation: 662

You'll have to use nested attributes to do this. Fortunately, Rails makes it pretty easy. Here's how to do it:

  1. First, signify to Office that you're giving it Location fields as well by adding this line: accepts_nested_attributes_for :location.

  2. Now, in new.html.erb, add the fields that you want. Say we want to have city and state:

    <%= f.fields_for :location do |ff| %>
        <%= ff.label :city %>
        <%= ff.text_field :city %>
    
        <%= ff.label :state %>
        <%= ff.text_field :state %>
    <% end %>
    

That's it!

Upvotes: 3

Related Questions