如果表名中有_,如何从rails控制台访问表

时间:2023-01-16 09:53:10

I am trying to access all records of a table that has an underscore in its name. For example if I have table in my schema that is called trips I can do Trip.all in rails console. But what do I do if my table name contains an underscore (e.g. users_foods)

我正在尝试访问一个名称中有下划线的表的所有记录。例如,如果我的模式中有一个表叫做trips,我可以进行Trip。在rails控制台。但是,如果我的表名包含下划线(例如users_foods),我该怎么办呢?

I tried the following options:

我尝试了以下选择:

Users_food.all
User_food.all
User_foods.all 
etc.

All of the above did not work, any suggestions?

以上都没用,有什么建议吗?

3 个解决方案

#1


3  

Figured it out One can access the data with UserFood

发现可以用UserFood访问数据

#2


0  

For a table named users_foods, ActiveModel should provide you with a corresponding Rails model UsersFood, to fit Ruby/Rails object naming convention. Try that.

对于名为users_foods的表,ActiveModel应该为您提供相应的Rails模型UsersFood,以适应Ruby/Rails对象命名约定。试试。

Class names Users_food or User_food, etc. do not conform to Ruby convention.

类名Users_food或User_food等不符合Ruby约定。

#3


0  

I had the same problem when creating bonus_histories table. And didn't work any of the answers until I found out why.

我在创建bonus_history表时遇到了同样的问题。直到我找到原因,我才找到答案。

I have made only rails g migration BonusHistory
and it was the problem. My rails console didn't find BonusHistory at all because I had no model.

我只做了rails g的迁移,这就是问题所在。我的rails控制台根本找不到BonusHistory,因为我没有模型。

So I had to first rollback the migration rake db:rollback STEP=1, then deleted the migration file and finally made

rails g model BonusHistory

and after migrating that table, when I enter rails console, I can successfully ask for BonusHistory.count

因此,我必须首先回滚迁移rake db:回滚步骤=1,然后删除迁移文件,最后制作rails g模型BonusHistory,在迁移那个表之后,当我进入rails控制台时,我可以成功地请求BonusHistory.count。count

#1


3  

Figured it out One can access the data with UserFood

发现可以用UserFood访问数据

#2


0  

For a table named users_foods, ActiveModel should provide you with a corresponding Rails model UsersFood, to fit Ruby/Rails object naming convention. Try that.

对于名为users_foods的表,ActiveModel应该为您提供相应的Rails模型UsersFood,以适应Ruby/Rails对象命名约定。试试。

Class names Users_food or User_food, etc. do not conform to Ruby convention.

类名Users_food或User_food等不符合Ruby约定。

#3


0  

I had the same problem when creating bonus_histories table. And didn't work any of the answers until I found out why.

我在创建bonus_history表时遇到了同样的问题。直到我找到原因,我才找到答案。

I have made only rails g migration BonusHistory
and it was the problem. My rails console didn't find BonusHistory at all because I had no model.

我只做了rails g的迁移,这就是问题所在。我的rails控制台根本找不到BonusHistory,因为我没有模型。

So I had to first rollback the migration rake db:rollback STEP=1, then deleted the migration file and finally made

rails g model BonusHistory

and after migrating that table, when I enter rails console, I can successfully ask for BonusHistory.count

因此,我必须首先回滚迁移rake db:回滚步骤=1,然后删除迁移文件,最后制作rails g模型BonusHistory,在迁移那个表之后,当我进入rails控制台时,我可以成功地请求BonusHistory.count。count