2010-03-11 17 views
1

我正在使用dwilkie的foreigner插件for rails。我有一個表創建語句看起來像:如何防止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_idgame_id - 不agents_idgames_id。如何防止Rails將列複數化?


我想在我的enviornment.rb文件下面,這並沒有幫助:

​​

回答

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的東西。

2

在一般情況下,不打的ActiveRecord的約定,這是什麼使AR工作這麼好一部分。但是,如果對於此一種情況您想要例外,那麼通過您的environment.rb中的某些代碼很容易,請查看http://api.rubyonrails.org/classes/Inflector/Inflections.html作爲示例。

+0

我在ActiveSupport :: Inflector.inflections中添加了| inflect | inflect.uncountable「agent_id」,「game_id」 end',但Rails仍然適用於複數列。 – Mike 2010-03-12 00:43:36

0

我想你會得到你想要的東西,如果你在引用中使用的單一型號名稱,就像這樣:

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,因此將參考一個遊戲的一個代理。

在這種情況下,不需要額外的變形或外鍵聲明。