简体   繁体   English

如何防止Rails“复数”列名?

[英]How can I prevent Rails from “pluralizing” a column name?

I'm using dwilkie's foreigner plugin for rails. 我正在使用dwilkie的外国人插件用于rails。 I have a table creation statement that looks like: 我有一个表创建语句,如下所示:

create_table "agents_games", :force => true, :id => false do |t|
  t.references :agents,     :column => :agent_id, :foreign_key => true, :null => false
  t.references :games,      :column => :game_id, :foreign_key => true, :null => false
end

However, this generates the following SQL: 但是,这会生成以下SQL:

[4;35;1mSQL (2.7ms)[0m [0mCREATE TABLE "agents_games" ("agents_id" integer NOT NULL, "games_id" integer NOT NULL) [0m

I want the columns to be called agent_id and game_id - not agents_id and games_id . 我希望列被称为agent_idgame_id - 而不是agents_idgames_id How can I prevent Rails from pluralizing the columns? 如何防止Rails复数列?


I tried the following in my enviornment.rb file, which didn't help: 我在我的enviornment.rb文件中尝试了以下操作,但没有帮助:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.uncountable "agent_id", "game_id"
end

In general, do not fight ActiveRecord's conventions, it's part of what makes AR work so well. 一般来说,不要与ActiveRecord的惯例作斗争,这是AR工作如此顺利的部分原因。 However, if for this one case you want to make an exception, it's easy enough via some code in your environment.rb, check out http://api.rubyonrails.org/classes/Inflector/Inflections.html for an example. 但是,如果对于这种情况你想要做一个例外,通过你的environment.rb中的一些代码很容易,请查看http://api.rubyonrails.org/classes/Inflector/Inflections.html以获取示例。

Found the solution to my issue. 找到了我的问题的解决方案。 I had to declare foreign keys separately from references like so: 我不得不像引用那样单独声明外键:

create_table "agents_games", :force => true, :id => false do |t|
  t.references :agent
  t.foreign_key :agents,     :column => :agent_id, :null => false
  t.references :game
  t.foreign_key :games,      :column => :game_id, :null => false
end

With this, I could take out the Inflector stuff. 有了这个,我可以拿出Inflector的东西。

I think you'll get what you want if you use the singular model name in the reference, like this: 如果您在参考中使用单数模型名称,我认为您将得到您想要的内容,如下所示:

create_table "agents_games", :force => true, :id => false do |t|
  t.references :agent,     :foreign_key => true, :null => false
  t.references :game,      :foreign_key => true, :null => false
end

This is a clearer way, reflecting that each row of your join table will have one agent_id and one game_id, thus will reference one agent with one game. 这是一种更清晰的方式,反映了连接表的每一行将有一个agent_id和一个game_id,因此将引用一个代理与一个游戏。

The additional inflection or foreign key declarations wouldn't be necessary in this case. 在这种情况下,不需要额外的变形或外键声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM