Question

I'm trying to scaffold an app with Rails 4 and I had this little issue with the foreing keys, forms and Entity names. Here are some details:

rails g scaffold user_type name:string
rails g scaffold user name:string pass:string user_type:references

As you can see there is a simple relationship 1:n between an user_type and a user. An it generates the right scaffold on this case. Here is an image of the form generated,

enter image description here

But what I want as a result of the generator is the next form,

enter image description here

So the first change that I want from rails g scaffold is to generate, at least e 1:n relationships with a select input. And also I'm looking for a solution that involves the Models with a label or something. I need a scaffold command that finally generates this.

enter image description here

Witch means that the Entity user_type has his name attribute has a "presentation label".

I understand that I can create a generator from scratch, but I believe that I'm missing some options at the command line, because the change actually really tiny.

And can come up with a solution that involves inserting the right code in each CRUD but i'm planning to use this into a 150 tables database. Any help?

Was it helpful?

Solution

You can replace the templates that the scaffold generator uses by creating alternative templates in a lib/templates/erb/scaffold folder in your application root.

In this case, you will want to copy the original _form.html.erb template and replace the text field with a collection_select:

  <%- if attribute.reference? -%>
    <%%= f.label :<%= attribute.column_name %> %><br>
-   <%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>
+   <%%= f.collection_select :<%= attribute.column_name %>, <%= attribute.name.camelize %>.all, :id, :name, prompt: true  %>
  <%- else -%>

More details can be read in my post on the subject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top