Search code examples
ruby-on-rails-4has-manybelongs-to

creating a record in a table automatically after saving the other record in tne other table rails4


I still novice with RoR. My mission is to add examplaries according to the number of exemplary inserted in the form of book, knowing that i have a book table and an examplary table and the relationship in between is a book has_many exemplaries and an exemplary belong_to a book. This is my attempt:

in books_controller.rb method create:

 def create
    @book= Book.new(book_params)

     if @book.save
      @book.nbr_exemplaires.times do |i|
        @exemplaire= Exemplaire.create(book_id:  @book.id, state: 0 )
      end

      flash[:notice]='goood'
      redirect_to admin_manage_path
     else
       flash[:alert]='ouups'
       redirect_to root_url
     end
  end



  private

   def book_params
     params.require(:book).permit(:title, :pages, :resume,:nbr_exemplaires, :has_exemplaires,       :author_ids =>[], :subject_ids =>[])
    end

book/new.html.erb:

<h1>Add new book</h1>
          <%= form_for(@book) do |form| %>
          <div> <%= form.label :title %><br>
            <%= form.text_field :title %>
     </div>
     <div>
       <%= form.label :pages %><br>
       <%= form.number_field :pages %>
      </div>
      <div>
         <%= form.label :resume %><br>
         <%= form.text_area :resume %>
      </div>
      <div>
       <p>select author from existing list</p><br>
         <%= form.collection_select :author_ids, @authors, :id, :l_name, {:selected => 1}, {:name => 'book[author_ids][]'} %>

     </div>
      <div>
         <p> Select subject from existing list</p><br>
           <%= form.collection_select :subject_ids, @subjects, :id, :name, {:selected =>1}, {:name => 'book[subject_ids][]'} %>
      </div>
      <div>
        <%= form.label :has_exemplaires? %>
         <%= form.check_box :has_exemplaires,{}, 'Yes', 'No'%>
           <div id="expl_details" style="display:none;">
            <%= form.label :nbr_exemplaires %> <%= form.number_field :nbr_exemplaires %>

          </div>
         </div>
         <%= form.submit "Submit" %>
       <% end %>
       <script type="text/javascript">
         var checkbox = document.getElementById('book_has_exemplaires');
         var details_div = document.getElementById('expl_details');
         checkbox.onchange = function() {
           if(this.checked) {
              details_div.style['display'] = 'block';
           } else {
             details_div.style['display'] = 'none';
           }
          };
         </script>

Solution

  • Then I would suggest something like this:

    class Book < ActiveRecord::Base
      has_many :exemplaires
    
      attr_accessor :nbr_exemplaires
      after_save :create_exemplaires
    
      private 
    
      def create_exemplaires
        nbr_exemplaires.times do
            self.exemplaires.create()
        end
      end
    

    If you actually have a column name 'nbr_exemplaires' in your table, you don't need the attr_accessor line. That is only if you won't be saving that as separate value in the DB.