加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 4迁移:has_and_belongs_to_many表名

发布时间:2020-12-16 19:59:47 所属栏目:百科 来源:网络整理
导读:我目前尝试将rails 3.2应用程序切换到rails 4.0.但是我有一个has_and_belongs_many模型的问题. 我已经创建了一个测试应用程序,我也有同样的问题.这就是我所做的: 创建了两个模型:foo_clip和foo_url class FooClip ActiveRecord::Base has_and_belongs_to_m
我目前尝试将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

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

解决方法

我通过将join_table名称添加到每个模型来解决问题,如:
has_and_belongs_to_many :foo_urls,:join_table => :foo_clips_foo_urls

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读