Alternative for accepts_nested_attributes_for - maybe virtus

后端 未结 4 643
萌比男神i
萌比男神i 2021-02-07 04:21

I\'m relatively new to rails and finally found the right way to use accepts_nested_attributes_for.

However, there are some serious resources on the web who

4条回答
  •  野性不改
    2021-02-07 05:07

    It's much easier to use virtus instead of accepts_nested_attributes_for than I thought. The most important requirement was to dare to make things that were not covered in any of the tutorials I read yet.

    Step by step:

    1. I added gem 'virtus' to the Gemfile and ran bundle install.
    2. I wrote a file models/contact.rb and wrote the following code:

      class Contact
        include Virtus
      
        extend ActiveModel::Naming
        include ActiveModel::Conversion
        include ActiveModel::Validations
      
        attr_reader :name
        attr_reader :number
      
      
        attribute :name, String
        attribute :number, Integer
      
        def persisted?
          false
        end
      
        def save
          if valid?
            persist!
            true
          else
            false
          end
        end
      
      private
      
        def persist!
          @person = Person.create!(name: name)
          @phones = @person.phones.create!(number: number)
        end
      end
      
    3. Then I ran rails generate controller contacts and filled *models/contacts_controller.rb* with

      class ContactsController < ApplicationController
      
        def new
      
          @contact = Contact.new
      
        end
      
        def create
      
          @contact = Contact.new(contact_params)
          @contact.save
          redirect_to people_path
      
        end
      
        def contact_params
      
          params.require(:contact).permit(:name, :number)
      
        end
      
      end
      
    4. The next step was the view. I created views/contacts/new.html.erb and wrote this basic form

      <%= form_for @contact do |f| %>
        

      <%= f.label :name %>
      <%= f.text_field :name %>

      <%= f.label :number %>
      <%= f.text_field :number %>

      <%= f.submit %> <% end %>
    5. Of course I also needed to add the route resources :contacts

    That's it. Maybe it could be done more elegant. Maybe it would also pay to use only the Contacts-class, also for the other CRUD-actions. I didn't try that yet...

    You can find all changes here: https://github.com/speendo/PhoneBook/tree/virtus/app/models

提交回复
热议问题