Rails 4 迁移:has_and_belongs_to_many 表名

26

我目前正在尝试将一个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 文件里有任何代码吗? - MurifoX
你可以看到种子文件的全部内容,里面没有其他代码。 - patrickS
“我已更新迁移”是什么意思 - 你改变了任何现有的迁移吗? - BroiSatse
是的,我已经添加了现有的内容,如果我在此之后删除、创建和迁移,这应该不会成为问题。对吗? - patrickS
如果在这些迁移之后还有其他迁移,可能会出现问题,因为它们可能依赖于给定的数据库状态,除非你百分之百确定会发生什么,否则不应更改现有迁移。那么,在你更改了这些迁移之后,是否还有其他迁移呢?你能把你的回溯信息也复制粘贴一下吗? - BroiSatse
我从零开始创建了这个Rails应用程序,只是为了演示问题,在这个Rails 4项目中没有其他内容。 - patrickS
1个回答

52
我通过在每个模型中添加join_table名称来解决了这个问题,类似于:
has_and_belongs_to_many :foo_urls,  :join_table => :foo_clips_foo_urls

1
更明确的例子请参考:http://ruby-journal.com/rails-4-changes-join-table-naming-convention/ - Greg Olsen
2
此外,您可以使用 has_and_belongs_to_many :my_foo_urls, :class_name => 'Foo_Url', :join_table => :foo_clips_foo_urls - mb21

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接