【问题标题】:Rails 4 Migration: has_and_belongs_to_many table nameRails 4 迁移:has_and_belongs_to_many 表名
【发布时间】:2014-02-28 05:23:06
【问题描述】:

我目前尝试将 rails 3.2 应用程序切换到 rails 4.0。但我对has_and_belongs_many 模型有一个问题。

我创建了一个测试应用程序,在那里我遇到了同样的问题。这就是我所做的:

创建了两个模型:foo_clip 和 foo_url

class FooClip < ActiveRecord::Base
  has_and_belongs_to_many :foo_urls

  attr_accessible :id, :name
end


class FooUrl < ActiveRecord::Base
  has_and_belongs_to_many :foo_clips

  attr_accessible :url
end

在此之后我更新了迁移文件:

class CreateFooClips < ActiveRecord::Migration
  def change
    create_table :foo_clips do |t|
      t.string :name
      t.timestamps
    end
  end
end

class CreateFooUrls < ActiveRecord::Migration
  def change
    create_table :foo_urls do |t|
      t.string :url
      t.timestamps
    end
  end
end

现在我已经为 has_and_belongs_to_many 表创建了迁移文件

class CreateFooClipsFooUrls < ActiveRecord::Migration
  def change
    create_table :foo_clips_foo_urls do |t|
      t.belongs_to :foo_url
      t.belongs_to :foo_clip
    end
  end
end

作为最后一步,我创建了一个用于测试的种子文件:

foourl1 = FooUrl.create!(:url => 'http://www.google.com')
foourl2 = FooUrl.create!(:url => 'http://www.apple.com')

fooclip1 = FooClip.create!(:name => 'TestClip1')

fooclip1.foo_urls << foourl1
fooclip1.foo_urls << foourl2

fooclip1.save

现在我做到了:

rake db:drop
rake db:create
rake db:migrate
rake db:seed

得到了这个错误:

PG::UndefinedTable: ERROR:  relation "foo_clips_urls" does not exist
LINE 5:         WHERE a.attrelid = '"foo_clips_urls"'::regcla...
                                          ^
:               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 = '"foo_clips_urls"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum

如果我查看 postgres 数据库,该表被称为:foo_clips_foo_urls

任何想法为什么会发生这种情况?

【问题讨论】:

  • 您的seed 文件中有代码吗?
  • 你看到了上面种子文件的全部内容,里面没有更多代码了。
  • I have updated migrations 是什么意思 - 您是否更改了任何现有的?
  • 是的,我已经添加了现有的,如果我在此之后删除、创建和迁移,这应该不是问题。还是?
  • 如果之后有任何迁移可能是个问题,因为它们可能依赖于给定的数据库状态,你不应该改变现有的迁移,除非你 100% 确定会发生什么。那么在你改变之后你有任何迁移吗?你也可以粘贴你的回溯吗?

标签: ruby-on-rails ruby postgresql ruby-on-rails-4


【解决方案1】:

我通过将 join_table 名称添加到每个模型来解决问题,例如:

has_and_belongs_to_many :foo_urls,  :join_table => :foo_clips_foo_urls

【讨论】:

猜你喜欢
  • 2011-09-27
  • 2020-10-28
  • 2011-05-21
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 2011-12-02
相关资源
最近更新 更多