2

I'm using dwilkie's foreigner plugin for 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:

[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. How can I prevent Rails from pluralizing the columns?


I tried the following in my enviornment.rb file, which didn't help:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.uncountable "agent_id", "game_id"
end
GiH
  • 14,006
  • 13
  • 43
  • 56
Mike
  • 23,892
  • 18
  • 70
  • 90

3 Answers3

2

In general, do not fight ActiveRecord's conventions, it's part of what makes AR work so well. 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.

Ana Betts
  • 73,868
  • 16
  • 141
  • 209
  • I added in `ActiveSupport::Inflector.inflections do |inflect| inflect.uncountable "agent_id", "game_id" end`, but Rails still goes for the plural column. – Mike Mar 12 '10 at 00:43
2

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.

Mike
  • 23,892
  • 18
  • 70
  • 90
1

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.

The additional inflection or foreign key declarations wouldn't be necessary in this case.

user2553863
  • 682
  • 1
  • 8
  • 17