将动态实例变量插入红宝石sqlite查询
我有一个问题,试图创建动态保存方法。此方法应适用于该父母方法的所有孩子。我已经设置了使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论