代码之家  ›  专栏  ›  技术社区  ›  Mike

如何防止rails将列名“复数”?

  •  1
  • Mike  · 技术社区  · 15 年前

    我在用德威基的 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_id game_id -不 agents_id games_id . 如何防止rails使列多元化?


    我在我的 enviornment.rb 不起作用的文件:

    ActiveSupport::Inflector.inflections do |inflect|
      inflect.uncountable "agent_id", "game_id"
    end
    
    3 回复  |  直到 9 年前
        1
  •  2
  •   Ana Betts    15 年前

    一般来说,不要违背activerecord的惯例,这是ar工作良好的一部分。但是,如果是这样的话 一例 如果您想创建一个异常,那么通过您环境中的一些代码就足够简单了。 http://api.rubyonrails.org/classes/Inflector/Inflections.html 举个例子。

        2
  •  2
  •   Mike    15 年前

    找到了解决我问题的办法。我必须分别声明外键和引用,例如:

    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
    

    有了这个,我可以去掉拐点。

        3
  •  0
  •   user2553863    9 年前

    我认为如果在引用中使用单一模型名,您将得到所需的结果,例如:

    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
    

    这是一种更清楚的方式,反映出联接表的每一行将有一个代理id和一个游戏id,因此将用一个游戏引用一个代理。

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