ActiveModel attribute for ActiveRecord has_attribute?

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?

+4
source share
1 answer

According to the above code example, you don’t need to use the ActiveModel method similar to has_attribute? at has_attribute? - you can just go back to simple ol 'Ruby:

 def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) if respond_to?("#{name}=") end end 

This only assigns an attribute if it was started using attr_accessor .

+4
source

All Articles