I have a model has nested attributes with another.
My question is: how better solution for call a build in controller or model?
See that model:
class ContentType < ActiveRecord::Base
after_initialize :add_fields
belongs_to :project
has_many :field_content_types
accepts_nested_attributes_for :field_content_types, reject_if: proc {|attributes| attributes['name'].blank?}
private
def add_fields
self.field_content_types.build if new_record?
end
end
Either remove after_initialize
in model and add line in controller
class ContentTypesController < ApplicationController
def new
@content_type = ContentType.new
@content_type.field_content_types.build
end
end
Have one reason to set build in controller?
Assuming you are asking where you should build field_content_types
, in this particular case, I don't think it matters whether you build it in model or controller.
The rule of thumb is to keep the controller thin and model fat, but the build method already so concise that you won't gain much from building it from model.
Personally, I would just build it in the controller.