2

我正在使用 dwilkie 的foreigner插件用于 rails。我有一个表创建语句,如下所示:

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

但是,这会生成以下 SQL:

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

我希望这些列被称为agent_idand game_id- not agents_idand games_id。如何防止 Rails 使列复数?


我在我的enviornment.rb文件中尝试了以下内容,但没有帮助:

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

3 回答 3

2

一般来说,不要与 ActiveRecord 的约定作对,这是让 AR 如此出色的部分原因。但是,如果对于这种情况,您想要例外,通过 environment.rb 中的一些代码很容易,请查看http://api.rubyonrails.org/classes/Inflections/Inflections.html以获取示例。

于 2010-03-12T00:11:46.463 回答
2

找到了我的问题的解决方案。我必须将外键与引用分开声明,如下所示:

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

有了这个,我可以取出 Inflector 的东西。

于 2010-03-12T02:00:19.200 回答
1

如果您在参考中使用单数型号名称,我认为您会得到您想要的,如下所示:

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

这是一种更清晰的方式,反映了连接表的每一行都有一个 agent_id 和一个 game_id,因此将引用一个代理与一个游戏。

在这种情况下,不需要额外的变形或外键声明。

于 2016-04-09T17:23:06.320 回答