Rails生成器脚手架定制,为什么模型和视图没有属性数据?

时间:2016-09-20 06:27:11

标签: ruby-on-rails ruby generator

当我运行“rails g account_scaffold account / student name:string age:integer”时,

模型和视图没有属性。

代码如下:

LIB /发电机/ account_scaffold / account_scaffold_generators.rb:

require 'rails/generators/resource_helpers'
require "rails/generators/model_helpers"

module Rails
  module Generators
    class AccountScaffoldGenerator < Rails::Generators::NamedBase

      include Rails::Generators::ModelHelpers
      include Rails::Generators::ResourceHelpers

      check_class_collision suffix: "Controller"

      argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]"

      class_option :disable_common, type: :boolean, default: false, desc: 'SETS: --no-helper --no-view-specs --no-request-specs --no-routing-specs'
      hook_for :orm, :in => :rails, :required => true, :as => :model do |invoked|
        invoke invoked, [singular_name]
      end

      def create_controller_files
        if @options[:disable_common]
          @options = @options.merge(helper: false)
        end
        template "controller.rb", File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb")
      end

      hook_for :template_engine, :test_framework, as: :scaffold do |invoked|
        controller_name_param = controller_class_path.blank? ? singular_name : (controller_class_path.join("/") + "/" + singular_name)
        if @options[:disable_common]
          invoke invoked, [ controller_name_param ], {view_specs: false, request_specs: false, routing_specs: false}
        else
          invoke invoked, [ controller_name_param ]
        end
      end

      hook_for :helper, as: :scaffold do |invoked|
        invoke invoked, [ controller_name ]
      end

      hook_for :assets do |assets|
        invoke assets, [controller_name]
      end

      hook_for :resource_route do |route|
        invoke route, [controller_name]
      end

    end
  end
end

LIB /模板/超薄/支架/ _form.html.slim

= simple_form_for(@<%= singular_name %>) do |f|
  .form-inputs
    <%- attributes.each do |attribute| -%>
      = f.<%= attribute.reference? ? :association : :input %> :<%= attribute.name %>
    <%- end -%>

  .form-actions
    = f.button :submit

1 个答案:

答案 0 :(得分:0)

我找到解决问题的最简洁方法是覆盖初始化程序。我的应用程序中有以下生成器:

module Rails::Generators
  class GrapesGenerator < ::Rails::Generators::ScaffoldGenerator
    attr_reader :fields

    def initialize(args, *options) #:nodoc:
      @fields = args[1..-1]
      super
    end

    hook_for :orm, as: :model do |instance, orm|
      instance.invoke orm, [ instance.options[:model_name], instance.fields ]
    end
  end
end