【问题标题】:How can I prevent Rails from "pluralizing" a column name?如何防止 Rails “复数”列名?
【发布时间】:2010-03-11 23:52:40
【问题描述】:

我正在使用 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_idgame_id - 而不是 agents_idgames_id。如何防止 Rails 使列复数?


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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-plugins foreigner


    【解决方案1】:

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

    【讨论】:

    • 我在ActiveSupport::Inflector.inflections do |inflect| inflect.uncountable "agent_id", "game_id" end 中添加了,但Rails 仍然使用复数列。
    【解决方案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 的东西了。

    【讨论】:

      【解决方案3】:

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

      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-12-07
        • 1970-01-01
        • 1970-01-01
        • 2017-06-12
        • 2015-04-26
        • 2022-10-05
        • 2017-06-08
        • 2016-09-04
        • 2022-08-21
        相关资源
        最近更新 更多