简体   繁体   English

ActiveRecord错误的table_name

[英]ActiveRecord wrong table_name

I'm trying to add an ActiveRecord model called Media. 我正在尝试添加名为Media的ActiveRecord模型。 The migration script looks like this 迁移脚本如下所示

class CreateMedias < ActiveRecord::Migration
   def up
      create_table :medias do |t|
         t.string :filename
         t.timestamps null: false
      end
   end
   def down
       drop_table :medias
   end
end

This will create a table in my PostgreSQL database called medias just as I expected. 这将在我的PostgreSQL数据库中创建一个名为medias的表,就像我预期的那样。 My ActiveRecord class looks like this 我的ActiveRecord类看起来像这样

class Media < ActiveRecord::Base

end

From what I understand this is how it should look like. 根据我的理解,它应该是这样的。 The name of the ActiveRecord class should in singular and the table name in plural. ActiveRecord类的名称应为单数,表名称应为复数。 However, when I try to create a new Media object 但是,当我尝试创建一个新的Media对象时

Media.create filename: "abc.png"

I get the following error 我收到以下错误

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation    "media" does not exist
LINE 5:                WHERE a.attrelid = '"media"'::regclass
                                      ^
:           SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                 pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
            FROM pg_attribute a LEFT JOIN pg_attrdef d
              ON a.attrelid = d.adrelid AND a.attnum = d.adnum
           WHERE a.attrelid = '"media"'::regclass
             AND a.attnum > 0 AND NOT a.attisdropped
           ORDER BY a.attnum

For some reason ActiveRecord thinks that the table_name should be media and not medias. 出于某种原因,ActiveRecord认为table_name应该是media而不是medias。 If I run the same query directly in the database with 'medias' instead of 'media' I get the expected result. 如果我使用'medias'而不是'media'直接在数据库中运行相同的查询,我会得到预期的结果。 For all my other models, the table_name is pluralized but for some reason my Media model is an exception. 对于我的所有其他模型,table_name是复数形式但由于某种原因我的Media模型是一个例外。 Does anyone know what might cause this? 有谁知道这会导致什么?

Media is a already a plural (it's the plural of medium), so active record pluralizes no further, even if people say "medias" often enough. 媒体已经是复数(它是复数的媒介),所以即使人们经常说“媒体”,积极的记录也不会进一步复杂化。

You can check how rails pluralizes things from the rails console 您可以从rails控制台检查rails是如何复杂化的

"medium".pluralize #=> "media"
"media".pluralize #=> "media"

If you disagree strongly and don't want to rename your table / model, you can either force active record to use your table name 如果您强烈反对并且不想重命名表/模型,则可以强制使用活动记录来使用表名

class Media < ActiveRecord::Base
  self.table_name = "medias"
end

or customise the inflections. 或自定义变形。 Your app should have a config/initializers/inflections.rb which sets out how to do this. 您的应用应该有一个config / initializers / inflections.rb,其中列出了如何执行此操作。

Extending @spickermann's comment, if you want to use Media as singular for medias , you should provide an inflection to declare it. 扩展@ spickermann的评论,如果你想使用Media作为单一的medias ,你应该提供一个拐点声明它。

file: /rails_root/config/initializers/inflections.rb 文件: /rails_root/config/initializers/inflections.rb

ActiveSupport::Inflector.inflections do |inflect|
  inflect.plural 'medias', 'media'
end

This way, you will be able to use this singular/plural relation throughout your whole app.. 这样,您就可以在整个应用程序中使用这种单数/复数关系。

If you generate model with the name of Media like this: 如果您生成名为Media模型,如下所示:

rails g model media filename:string

then ActiveRecord will generate it's table as media only not medias 然后ActiveRecord将生成它的表作为media而不是medias

Here is it's migration file: 这是它的迁移文件:

class CreateMedia < ActiveRecord::Migration
  def change
    create_table :media do |t|
      t.string :filename

      t.timestamps null: false
    end
  end
end

In your case ActiveRecord is looking for media and you have defined table name as medias that's why you are getting an error. 在您的情况下, ActiveRecord正在寻找media ,您已将表名定义为medias ,这就是您收到错误的原因。

So you can set table name explicitly in model as: 因此,您可以在模型中显式设置表名:

Rails >= 3.2 (including Rails 4+): Rails> = 3.2(包括Rails 4+):

class Media < ActiveRecord::Base
  self.table_name = "medias"
end

Rails <= 3.1: Rails <= 3.1:

class Media < ActiveRecord::Base
  self.set_table_name "medias"
end

For more details please refer this: http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name 有关详细信息,请参阅: http//api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name


You can also change the table name by generating new migration file: 您还可以通过生成新的迁移文件来更改表名:

class RenameOldTableToNewTable< ActiveRecord:Migration
   def change
     rename_table :old_table_name, :new_table_name
   end 
 end 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ActiveRecord table_name线程安全吗? - Is ActiveRecord table_name thread safe? ActiveRecord是否缓存table_name? - Does ActiveRecord cache table_name? 在ActiveRecord :: Base子类中设置table_name - Setting table_name in ActiveRecord::Base subclass rails - activerecord SELECT TOP 1 field_name * FROM table_name - rails - activerecord SELECT TOP 1 field_name * FROM table_name 我可以在ActiveRecord(或Mongoid)中为数据库连接和table_name配置线程安全的每个请求配置吗? - Can I have thread safe per-request configuration for database connection and table_name in ActiveRecord (or Mongoid)? 具有设计的表用户的自定义table_name - custom table_name for table users with devise Extent ActionText::RichText 覆盖 table_name - Extent ActionText::RichText to override table_name Rails HBTM join_table覆盖table_name - Rails HBTM join_table overwirting table_name Mysql :: Error:表&#39;table_name&#39;被标记为崩溃,应该修复 - Mysql::Error: Table 'table_name' is marked as crashed and should be repaired Mysql2::Error: 表 &#39;table_name&#39; 不存在:显示来自 `table_name` 的完整字段 - Mysql2::Error: Table 'table_name' doesn't exist: SHOW FULL FIELDS FROM `table_name`
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM