How to update multiple models using rails

I have two models

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

I have new.html.erb for an office model and 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 to add fields for Location model in new.html.erb from Office ?

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

+4
source share
1 answer

To do this, you will need to use nested attributes. Fortunately, Rails makes this pretty easy. Here's how to do it:

  • First, indicate in Office that you also specify Location fields by adding this line: accepts_nested_attributes_for :location .

  • Now in new.html.erb add the required fields. Say we want to have a city and state:

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

What is it!

+3
source

Source: https://habr.com/ru/post/1369405/


All Articles