Rails scaffold_controller生成器不会将模型属性应用于视图

我在具有现有属性的现有模型上使用scaffold_controller生成器,但生成的视图表单没有相应模型属性的任何输入控件 – 它们只是空表单。 这是为什么?

例如:

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

用户已经拥有nameemail属性的位置应生成包含姓名和电子邮件字段的表单…

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

 rails g scaffold_controller User name email 

我同意,当信息只是坐在模型中时,必须自己键入所有属性,存在拼写错误的名称或类型的危险。 这是我编写的用于插入列名称和类型的猴子补丁(至少在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  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