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...
This is what it is supposed to do. When calling scaffold_controller
you're telling the generator to not use a model. If you want to have form attributes in the views, you need to pass them to the generator just like you would a normal scaffolding.
rails g scaffold_controller User name email
In rails 5, you can get the list of columns with type using following code.
Model.columns.reject{|n| n.name == "id" or n.name == "created_at" or n.name == "updated_at" }.map{|i| "#{i.name}:#{i.type}"}.join(" ")
Later you can paste the output post rails g scaffold_controller
Model
I agree that it sucks to have to keyboard all the attributes yourself, with the danger of misspelling name or type, when the info is just sitting there in the model. Here is a monkey patch I wrote to interpolate the column names and types (at least in Rails 4). Put this code in an .rb file in the #{Rails.root}/config/initializers directory:
# 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With