vanderleipinto / preparation_mentorship

0 stars 0 forks source link

feat: create Assembly model, create migrations to assemblies_books and #18

Closed vanderleipinto closed 9 months ago

vanderleipinto commented 9 months ago

Create the entity

rails generate scaffold Assembly name

Create Migration that create the joins tables to book and part

assemblies_books
rails generate migration CreateJoinTableAssembliesBokks assembly book

assemblies_parts rails generate migration CreateJoinTableAssembliesParts assembly part

Migrate database

rails db:migrate

Alter Assembly model to relation to books and parts

class Assembly < ApplicationRecord
  has_and_belongs_to_many :books
  has_and_belongs_to_many :parts  
end
class Book < ApplicationRecord
  belongs_to :author
  has_and_belongs_to_many :assemblies
end
class Part < ApplicationRecord
  belongs_to :supplier
  has_and_belongs_to_many :assemblies
end

Insert the link in navbar

Added the following lines to do this:

<div class="Assemblies" style="padding: 10px">
    <%= link_to "Assemblies", assemblies_path %>
</div>

Change the view archive to show the other related entity.

In the file: app/views/assemblies/_form.html.erb

    <div >
    <%= form.label :parts, "Select Parts" %>
    <% Part.all.each do |part| %>
      <div class="checkbox">
        <%= check_box_tag "assembly[part_ids][]", part.id, @assembly.parts.include?(part) %>
        <%= label_tag "assembly_part_ids_#{part.id}", part.name %>
      </div>
    <% end %>
  </div>

This will show the name of the parts to insert in the assembly. These params have to be permited in the controller file.

In the file: app/controllers/assemblies_controller.rb

...
    def assembly_params
      params.require(:assembly).permit(:name, part_ids: [])
    end
...

This will permit the params part_ids: [] to be inserted into the new object.

In the file: app/views/books/_form.html.erb

  <div>
    <p><%= form.label :assembly_ids, "Select the assemblies:" %></p>
    <% Assembly.all.each do |assembly| %>
      <% if @book.assemblies.exists?(assembly.id) %>
        <%= form.check_box :assembly_ids, { multiple: true, checked: true }, assembly.id, nil %>
      <% else %>
        <%= form.check_box :assembly_ids, { multiple: true }, assembly.id, nil %>
      <% end %>
      <%= form.label :assembly_ids, assembly.name %><br>
    <% end %>
  </div>

This will show the name of the assemblies to be inserted in the book assemblies. These params have to be permited in the controller file.

In the file: app/controllers/books_controller.rb

    # Only allow a list of trusted parameters through.
    def book_params
      params.require(:book).permit(:name, :description, :author_id, assembly_ids: [])
    end

This will permit the params assembly_ids: [] to be inserted into the new object.