Home > Blockchain >  Ruby on rails assigning related objects to another
Ruby on rails assigning related objects to another

Time:07-18

What I'm trying to accomplish is to make function that will assign specific accounts to user. If user is admin he will get all the accounts for his company and if he is callaborator he will get only selected ones from the company. Parsed data is user object and array accounts containing account_id. I wrote this function that allows me to convert account_id into object and then assign it to user. The one problem is that when the accounts array has only one object I will get error

undefined method `each' for #<Account

Can someone tell me how to avoid that? Or suggest me different better approach to make this function.

Function that I wrote:

def assign_matching_accounts
    if @user.collaborator?
      accounts.map! do |account|
        Account.find_by(id: account['account_id'], company_id: @user.company_id)
      end
      accounts.compact!.uniq!
    elsif @user.admin?
      accounts = Account.find_by(company_id: @user.company_id)
    end
    @user.accounts = accounts unless accounts.nil?
  end

classes

Account:
  has_and_belongs_to_many :users
User:
  has_and_belongs_to_many :accounts

CodePudding user response:

Easiest fix is just to wrap it in an array, that way you can iterate over it.

[Account.find_by(company_id: @user.company_id)]
  • Related