Class: ScaffoldPlus::Generators::HasOneGenerator

Inherits:
ActiveRecord::Generators::Base
  • Object
show all
Defined in:
lib/generators/scaffold_plus/has_one/has_one_generator.rb

Instance Method Summary collapse

Instance Method Details

#add_migrationObject



29
30
31
32
# File 'lib/generators/scaffold_plus/has_one/has_one_generator.rb', line 29

def add_migration
  return unless options.migration?
  migration_template 'child_migration.rb', "db/migrate/#{migration_name}.rb"
end

#add_to_modelsObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/generators/scaffold_plus/has_one/has_one_generator.rb', line 34

def add_to_models
  inject_into_class "app/models/#{name}.rb", class_name do
    text = before_array.include?(name) ? "\n" : ""
    text << "  has_one :#{child}"
    text << ", inverse_of: :#{name}" if options.inverse?
    text << ", dependent: :#{dependent}" if options.dependent
    text << "\n"
    if options.nested
      text << "  accepts_nested_attributes_for :#{child}, allow_destroy: true\n"
    end
    text << "\n" if after_array.include?(name)
    text
  end

  inject_into_class "app/models/#{child}.rb", child.camelize do
    text = before_array.include?(child) ? "\n" : ""
    text << "  belongs_to :#{name}"
    if options.foreign_key
      text << ", foreign_key: \"#{options.foreign_key}\""
    end
    text << ", inverse_of: :#{child}" if options.inverse?
    text << "\n"
    text << "\n" if after_array.include?(child)
    text
  end
end

#add_to_permitObject



61
62
63
64
65
66
67
68
69
# File 'lib/generators/scaffold_plus/has_one/has_one_generator.rb', line 61

def add_to_permit
  return unless options.nested
  list = options.nested.map{|n| ":#{n}"}.join(', ')
  text = ":#{child}, #{child}_attributes: [ #{list} ]"
  file = "app/controllers/#{table_name}_controller.rb"
  gsub_file file, /(permit\(.*)\)/, "\\1, #{text})"
  # Special case: no previous permit
  gsub_file file, /^(\s*params)\[:#{name}\]$/, "\\1.require(:#{name}).permit(#{text})"
end