ActiveModel 相当于 ActiveRecord has_attribute?

发布于 2024-11-14 00:22:33 字数 694 浏览 1 评论 0原文

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等数载,海棠开 2024-11-21 00:22:33

根据上面的代码示例,您根本不需要使用类似于 has_attribute? 的 ActiveModel 方法——您可以简单地退回到普通的 Ruby:

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

这只会在以下情况下分配属性 :它是通过 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:

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

This will only assign the attribute if it has been initiated with attr_accessor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文