← Back to Upcase

Help using fields_for


(Scott Hollinshead) #1

I have created a form, and have decided to split out certain fields into there own models.

I have created an Address model which belongs_to :job_sheet, I have 2 other models in there too.

My question is, is there a way of creating a new Address without specifying it in my controller as my new action is getting quite big, this is what I have in my new action:

  def new
    @company = find_company
    @job_sheet = @company.job_sheets.new(user: current_user)
    @job_sheet.products.new
    @job_sheet.vehicles.new
    @job_sheet.build_customer_address
    @users = User.all
  end

Another reason I would like to know if that is possible is, because not all of my forms have products or vehicles.

Thanks


(Matthew Sumner) #2

You could abstract this into the model:

class JobSheetsController < ApplicationController
...
  def new
    @company = find_company
    @job_sheet = JobSheet.setup(@company, current_user)
    @users = User.all
  end
...
end

class JobSheet < ActiveRecord::Base
...
  def self.setup(company, user, with=[:products, :vehicles])
    job_sheet = company.job_sheets.new(user: user)
    job_sheet.instantiate(with)
    job_sheet.build_customer_address
    job_sheet
  end

  def instantiate(with)
    with.map do |association|
      self.send(association).new
    end
  end
...
end

Then use nested model forms as discussed in this railscast.

I would love to see some other solutions though.


(Luís Ferreira) #3

You can use a form object that abstracts the fact that you have a form for multiple models: http://robots.thoughtbot.com/activemodel-form-objects

I don’t like using nested attributes it feels clumsy to add stuff to the model just because of the way you build your forms. I tend to go you form objects instead.