我在具有现有属性的现有模型上使用scaffold_controller生成器,但是生成的视图表单没有相应模型属性的任何输入控件 - 它们只是空表单。这是为什么?
例如:
rails generate scaffold_controller User --skip --no-test-framework
用户已有name
和email
属性的位置应生成包含姓名和电子邮件字段的表单...
答案 0 :(得分:35)
这是应该做的。在调用scaffold_controller
时,您告诉生成器不使用模型。如果你想在视图中有表单属性,你需要像普通的脚手架一样将它们传递给生成器。
rails g scaffold_controller User name email
答案 1 :(得分: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
答案 2 :(得分:0)
在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(" ")
稍后,您可以粘贴输出接线柱g scaffold_controller
模型