从表名称中查找模型名称(Sequel ORM)
在 ruby 脚本中,我正在运行一个循环,在该循环中我动态地从表列表中获取表名,并且必须对其执行某种 CRUD 操作(主要是插入)。 我正在使用 Sequel Orm 并为各种表创建了模型。 如何找到每个表的模型名称以便我可以执行插入?
tables=["table1","table2",'table3",...] tables.each do |t| #perform insertion on t #how to find the model name for table t? end
我可以使用哈希来存储每个表的模型名称,或者可以遵循某种模式,例如将每个表的第一个字符转换为大写或类似的内容。
有更好的方法吗?
In a ruby script I am running a loop in which I am dynamically getting a table name from a list of tables and have to perform some sort of CRUD operation (mainly insertion) on it.
I am using Sequel Orm and have created models for the various tables.
How do I find the name of the Model for each table so that I can perform the insertion?
tables=["table1","table2",'table3",...] tables.each do |t| #perform insertion on t #how to find the model name for table t? end
I can use a hash to store the model names for each table or can follow a pattern like converting the first character of each table to uppercase or something like that.
Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在一般情况下,如果没有强力搜索,您所要求的就是不可能的,即使如此,它也是含糊不清的,原因很简单,以下内容是有效的:
基本上,每个模型都有一个相关的数据集(通常只是一个简单的 SELECT * FROM桌子)。然而,其他模型可以使用相同或相似的数据集。因此,从模型到表很简单,但从表到模型则不然。
如果您创建了自己的模型,处理您想要的内容的最简单方法是使用哈希:
然后您可以这样做:
在每个块内获取模型类。
What you are asking is not possible in the general case without a brute force search, and even then it is ambiguous, for the simple reason that the following is valid:
Basically, each model has a related dataset (usually just a simple SELECT * FROM table). However, other models can use the same or similar dataset. So going from model to table is simple, but table to model is not.
If you've created your own models, the easiest way to handle what you want is to use a hash:
Then you can just do:
inside that each block to get the model class.
只要模型和表之间遵循复数约定,从表名称获取模型名称的一种方法是:
但是,它看起来并不是您想要做的。您需要插入新的或更新现有的记录。由于您已经有了表名称,因此您可能希望考虑执行以下操作:
但是,您可能希望考虑 Jeremy Evans(其答案在上面)是 Sequel gem 的创建者,并且如果他不推荐将此作为解决方案那么可能有一个很好的理由。
One way to get the model name from the table name, as long as pluralization conventions have been followed between your models and tables, is something like:
However it doesn't look like that's what you're trying to do. You need to insert new or update existing reords. Since you already have the table name, you may wish to consider doing something like:
However you may wish to consider that Jeremy Evans, whose answer is above, is the creator of the Sequel gem and if he didn't recommend this as a solution then there may be a good reason.