Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Scaffold references with select input and Entity label with generators

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?

like image 618
Danilo Aburto Vivians Avatar asked Mar 20 '23 17:03

Danilo Aburto Vivians


1 Answers

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.

like image 169
Daniel Fone Avatar answered Apr 06 '23 08:04

Daniel Fone