ActiveModel 相当于 ActiveRecord has_attribute?
我使用 ActiveModel 是因为我连接到第三方 API 而不是数据库。我编写了自己的初始化程序,以便可以传入哈希并将其转换为模型上的属性 - 以支持应用程序中的某些表单。
attr_accessor :Id, :FirstName, :LastName,...
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
问题是我想使用相同的模型来处理来自 API 的数据检索,但这有大量我并不真正关心的其他数据。因此,我想在迭代从 API 返回的哈希时进行检查,并检查该属性是否存在于我的模型中,如果不存在则忽略它。这应该允许我为表单帖子和从 API 返回的数据拥有一致的模型。比如:
def initialize(attributes = {})
attributes.each do |name, value|
if self.has_attribute?(name)
send("#{name}=", value)
end
end
end
我已经浏览了 ActiveModel API 文档,但似乎没有等效的。这让我觉得我应该采取不同的做法。
这是正确的(Rails)方法吗?当数据来自不同来源时,如何确保模型属性一致?
I am using ActiveModel because I am hooking up to a third party API rather than a db. I have written my own initialiser so that I can pass in a hash and this be converted to attributes on the model - to support some of the 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 the data retrieval from the API, but this has a load of other data I don't really care about. As such I want to check as I iterate through the hash returned from the API and check if the attribute exists on my model and if not then just ignore it. This should allow me to have a consistent model for both the form posts and the data returned from the API. Something like:
def initialize(attributes = {})
attributes.each do |name, value|
if self.has_attribute?(name)
send("#{name}=", value)
end
end
end
I have looked through the ActiveModel API docs but there doesn't seem to be an equivalent. This is making me feel as though I should be doing this differently.
Is this the right (Rails) way to do this? How do I ensure I have consistent model attributes when the data is coming from different sources?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据上面的代码示例,您根本不需要使用类似于
has_attribute?
的 ActiveModel 方法——您可以简单地退回到普通的 Ruby:这只会在以下情况下分配属性 :它是通过
attr_accessor
启动的。Based on the code example above, you don't need to use an ActiveModel method similar to
has_attribute?
at all--you can simply fall back to plain ol' Ruby:This will only assign the attribute if it has been initiated with
attr_accessor
.