Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you generate the form for an existing model in Rails?

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

Working in Rails 3.

Thanks.

like image 313
B Seven Avatar asked Jul 11 '11 00:07

B Seven


People also ask

What does rails generate do?

Rails generators are command line tools that are used for automating the process of creating or editing files with boiler plate code. In essence, they execute Ruby code much like a script and create or update files based on templates, user input and whatever logic necessary.


1 Answers

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.

like image 106
Sam Ruby Avatar answered Nov 15 '22 01:11

Sam Ruby