20

I'm using the scaffold_controller generator on an existing model with existing attributes, but the view forms that get generated don't have any input controls for the corresponding model attributes - they're just empty forms. Why is that?

e.g:

rails generate scaffold_controller User --skip --no-test-framework

Where the User already has name and email attributes should generate forms with name and email fields...

4

3 回答 3

41

这是它应该做的。打电话时scaffold_controller,您是在告诉生成器不要使用模型。如果你想在视图中有表单属性,你需要像普通脚手架一样将它们传递给生成器。

rails g scaffold_controller User name email
于 2013-08-06T16:18:24.763 回答
7

在 rails 5 中,您可以使用以下代码获取具有类型的列列表。

Model.columns.reject{|n| n.name == "id" or n.name == "created_at" or n.name == "updated_at" }.map{|i| "#{i.name}:#{i.type}"}.join(" ")

稍后您可以粘贴输出 post rails gscaffold_controller模型

于 2019-05-27T05:32:09.740 回答
3

我同意,当信息就在模型中时,必须自己输入所有属性是很糟糕的,并且存在拼写错误名称或类型的危险。这是我编写的一个猴子补丁,用于插入列名和类型(至少在 Rails 4 中)。将此代码放在 #{Rails.root}/config/initializers 目录中的 .rb 文件中:

# patch to scaffold_controller to read model attributes
# if none specified on command line (and model exists)
# usage: rails g scaffold_controller <MODEL>

if ARGV.size > 0 and ARGV[0] == "scaffold_controller"
    puts "\n\n\n\n"
    puts "monkey patch attributes at #{Time.now}"

    Rails::Generators::NamedBase.class_eval do

        # parse_attributes! converts name:type list into GeneratedAttribute array
        # must be protected; thor enumerates all public methods as commands
        # and as I found out will call this and crash otherwise
        protected
        def parse_attributes! #:nodoc:
          # get model columns into col:type format
          self.attributes = get_model_attributes if not self.attributes or self.attributes.empty?
          # copied from default in named_base.rb
          self.attributes = (self.attributes || []).map do |attr|
            Rails::Generators::GeneratedAttribute.parse(attr)
          end
        end

        # get model columns if no attributes specified on command line
        # fake it by creating name:type args
        private
        def get_model_attributes
            # fill from model
            begin
                mdl = class_name.to_s.constantize
                # don't edit id, foreign keys (*_id), timestamps (*_at)
                attrs = mdl.columns.reject do |a|
                    n = a.name
                    n == "id" or n.end_with? "_id" or n.end_with? "_at"
                end .map do |a|
                    # name:type just like command line
                    a.name+":"+a.cast_type.type.to_s
                end
                puts "model_attributes(#{class_name})=#{attrs}"
                return attrs
            rescue => ex
                puts ex
                puts "problem with model #{class_name}"
                return nil
            end
        end

    end

end
于 2016-02-01T02:42:00.157 回答