How do you generate the form for an existing model

2019-03-30 05:06发布

问题:

What is the command to generate a single file (_form.html.erb) for an existing model?

Working in Rails 3.

Thanks.

回答1:

This may sound silly, but hear me out... I've done things like this a few times myself when I wanted to start clean. Following is a script that will read your schema and produce the necessary generate commands to reproduce it:

require 'rubygems'
require 'active_support/core_ext'
schema = File.read('db/schema.rb')
schema.scan(/create_table "(\w+)",.*?\n(.*?)\n  end/m).each do |name, ddl|
  puts "rails generate scaffold #{name.classify} " +
    ddl.scan(/t\.(\w+)\s+"(\w+)"/).
    reject {|type,name| %w(created_at updated_at).include? name}.
    map {|type,name| "#{name}:#{type}"}.join(' ')
end

If you run this, you will get a series of commands. In a new directory, create a new rails application, and then run these commands (simply copying and pasting them will do). Grab the files you want. Delete the directory when you are done.



回答2:

I don't believe there is a command to generate a single file... only an entire scaffold.

Is there a reason you want to generate that file? Are you unsure of what the contents should be?



回答3:

You can use this "reverse scaffold" script:

https://github.com/ahe/reverse_scaffold

It will generate the required html.erbb file right in your app/views folder.

It pretty well explained on the Readme page.

And, it's updated for Rails 3.2



回答4:

if you don't already have the controller for your model you can generate the controller, specify your entry points and it will create the views for you, however, if you want to have the _form.html.* file already written with the "ugly" default view you probably have to use scaffold to do it.

here's a good guide on generators and other rails command line options.