将动态实例变量插入红宝石sqlite查询

发布于 2025-01-26 23:18:27 字数 641 浏览 1 评论 0原文

我有一个问题,试图创建动态保存方法。此方法应适用于该父母方法的所有孩子。我已经设置了使用instance_variable_set和a哈希动态设置的实例变量。这是我现在存在的保存方法:

def save
  if DB.execute("SELECT id FROM '#{self.class.name.downcase}s' WHERE id = ?", @id).empty?
    DB.execute("INSERT INTO '#{self.class.name.downcase}s' (url, votes, title) VALUES (?, ?, ?)", @url, @votes, @title)
    @id = DB.last_insert_row_id
  else
    DB.execute("UPDATE '#{self.class.name.downcase}s' SET url = ?, votes = ?, title = ? WHERE id = ?", @url, @votes, @title, @id)
  end
end

如您所见,变量当前具有设置号(由查询中的问号确定)和设置名称(由变量名称确定)。我该如何做到这一点,以便使用任何数量的实例变量和名称并保存它们?

I have a problem trying to create a dynamic save method. This method should work for all children of this parent method. I have set the instance variables to be set dynamically using instance_variable_set and a hash. This is my save method as it exists now:

def save
  if DB.execute("SELECT id FROM '#{self.class.name.downcase}s' WHERE id = ?", @id).empty?
    DB.execute("INSERT INTO '#{self.class.name.downcase}s' (url, votes, title) VALUES (?, ?, ?)", @url, @votes, @title)
    @id = DB.last_insert_row_id
  else
    DB.execute("UPDATE '#{self.class.name.downcase}s' SET url = ?, votes = ?, title = ? WHERE id = ?", @url, @votes, @title, @id)
  end
end

As you can see, the variables currently have a set number (determined by the number of question marks in the query) and set names (determined by the variable names). How do I make it so that it will take any number of instance variables and names and saves them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文