I use ActiveModel because I connect to a third-party API, not db. I wrote my own initializer to pass the hash, and it will be converted to model attributes - to support some forms in the application.
attr_accessor :Id, :FirstName, :LastName,... def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end
The problem is that I want to use the same model to handle data retrieval from the API, but I have a ton of other data that I really don't need. So I want to check how I repeat the hash returned from the API and check if the attribute exists in my model, and if not, just ignore it. This should allow me to have a consistent model for both the form entries and the data returned from the API. Sort of:
def initialize(attributes = {}) attributes.each do |name, value| if self.has_attribute?(name) send("#{name}=", value) end end end
I looked at the ActiveModel API docs, but it looks like they are not equivalent. It makes me feel like I have to do it differently.
Is this the correct (Rails) way to do this? How can I provide consistent model attributes when data comes from different sources?
source share