I’m creating a custom controller generator that derives from Rails::Generators::NamedBase that creates both a controller and views given a particular model name (e.g. Person). I also want to create a _form.html.haml partial that builds a form based on the model’s attributes (I’m using simple_form btw).
What I have so far is:
<% attributes = file_name.capitalize.constantize.columns.map { |c| [Rails::Generator::GeneratedAttribute.new(c.name, c.type)]} %>
- simple_form_for [:admin,@<%=file_name%>] do |f|
= render 'shared/error_summary', :object => f.object
.inputs
<%- attributes.each do |attribute| -%>
= f.<%= attribute.reference? ? :association : :input %> :<%= attribute.name %>
<%- end -%>
.actions
= f.button :submit
I’m getting an “uninitialized constant Rails::Generator (NameError)” exception. Not sure what I need to require or if my approach above is even right.
Any help would be awesome.
Thanks -wg
I suspect the problem is that you are missing an s after Generator. The correct method call is:
Instead of creating your attributes variable inside your template, it is better to create it inside your generator class in the initialize method. This method looks like this as a skeleton:
If you are getting your user to pass in the desired attributes in the form column_name:column_type then you can do the following:
You might want to also handle the possibility that no attributes are passed in somehow. This will depend on your needs however so I can’t guide you on that without more information. Sorry!
A good model standard to follow is the nifty_generators source.