Mike W
Mike W

Reputation: 401

model attributes not persisted rails

I have a model Bank which has a persisted attribute called iban The data is sent to a third-party.

I'd like to make iban not persisted in the database, and fetch the information from the 3rd party every time.

what I've done is this :

class Bank < ActiveRecord::Base
   [...]
    attr_writer :iban

    before_save :send_to_service_provider

    def iban
       ServiceProvider::BankAccount.fetch(user_id)
    end

    def send_to_service_provider
       ServiceProvider::BankAccount.create(iban: iban, user_id: user.id)
    end
end

The problem is that when I get iban in send_to_service_provider it calls my method and doesn't get the value that I've passed

I need to keep the getter and the setter with the name iban, because this is part of an API, and I don't want to have to refactor my front, and my apps

thanks a lot for your help

Upvotes: 0

Views: 231

Answers (1)

mtrolle
mtrolle

Reputation: 2284

Consider using instance variables:

class Bank < ActiveRecord::Base
  [...]

  before_save :send_to_service_provider

  def iban
    ServiceProvider::BankAccount.fetch(user_id)
  end

  def iban=(value)
    @iban = value
  end

  def send_to_service_provider
    ServiceProvider::BankAccount.create(iban: @iban, user_id: user.id)
  end
end

This way you could even consider caching the ServiceProvider:

  def iban
    @iban ||= ServiceProvider::BankAccount.fetch(user_id)
  end

Upvotes: 1

Related Questions