Home > Back-end >  Rails: How to save and update array in bank with service
Rails: How to save and update array in bank with service

Time:04-19

I'm new to Rails and an English student, I'm using Google Translate to post here.

I wanted to know how to save an array of CNAES and if I'm using the correct relationship:

This is the bank: image-database

models - relationships:
class User < ApplicationRecord
  has_many :user_cnae_classifications
  has_many :cnae_classifications, through: :user_cnae_classifications
end
class CnaeClassification < ApplicationRecord
  belongs_to :user
  belongs_to :cnae_classification

  has_many :user_cnae_classifications
  has_many :users, through: :user_cnae_classifications
end

My users_controller calls the service:

  def create
    @user = User.new(user_params)
    if @user.save
      SaveUserCnaeClassifications.new(@user, user_cnae_classifications_param).call

      render json: @user, status: 200
    else
      render json: {errors: @user.errors}, status: 422
    end
  end

private
  def user_cnae_classifications_param
    param = params.require(:user).permit(
      cnae_classifications: []
    )
param[:cnae_classifications]
  end

This is the service that I am not able to save - under construction

class SaveUserCnaeClassifications
  def initialize(user, cnae_classifications)
    @user = user
    @cnae_classifications = cnae_classifications
  end

  def call
    return if @cnae_classifications.nil?
      
    user.cnae_classifications != cnae_classifications
  end

  private
 
end

Is my relationship correct? How did I save the CNAES array in my service? CNAE = identification number of the type of service that a company provides in Brazil.

a user may have multiple CNAEs and may update the CNAES as needed.

Any website/blog/tips for related studies will be of great help. Thanks

CodePudding user response:

You can use accepts_nested_attributes

Example:

class User < ApplicationRecord
  has_many :user_cnae_classifications
  has_many :cnae_classifications, through: :user_cnae_classifications

  accepts_nested_attributes_for :cnae_classifications
end

You don't need the class SaveUserCnaeClassifications.

  • Related