找不到桌子

时间:2013-11-13 17:41:52

标签: ruby-on-rails ruby sqlite activerecord

我不明白为什么会收到错误:

could not find table libraryusers10s 

在下面的代码中,我定义了两个表library_users10library_books10,并将它们与类关联。

以下代码可以正常使用:

require 'active_record'
ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3",
    :database => "library8")

ActiveRecord::Schema.define do
  create_table :library_users10 do |table|
    table.column :user_id, :integer
    table.column :name, :string
    table.column :age, :string
    table.column :books_borrowed, :integer
  end

  create_table :library_books10 do |table|
    table.column :books_id, :integer
    table.column :borrower_id, :integer
    table.column :title, :string
    table.column :borrowed, :string
    table.column :due_back, :string
  end
end

class LibraryUsers10 < ActiveRecord::Base
  has_many :library_books9s
end

class LibraryBooks10 < ActiveRecord::Base
  belongs_to :library_users10s
end

但是当我尝试填充表格时,通过在脚本中添加以下代码,我收到错误could not find table libraryusers10s

libraryusers10 = LibraryUsers10.create(:user_id => 1, :name => 'Tom', :age => 10, :books_borrowed => 3 )
libraryusers10.library_books10.create(:borrower_id => 1, :title => 'Who let the dogs out?', :borrowed => '13_November_2013', :due_back => '21_November_2013' )

有没有人对这里出了什么问题有任何建议?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

Rails约定用于表名复数

create_table :library_users10s do |table|
  ...

create_table :library_books10s do |table|
  ...

会为你解决问题。

如果你不能这样做,那么你可以在你的模型中添加一个修改器来跳过这样的变形器:

class LibraryUsers10 < ActiveRecord::Base
  self.table_name = 'library_users10'
  ...

答案 1 :(得分:1)

我可以猜到的是因为Class的末尾有'S'。例如:

Person.all查询人员表。

我想如果你在创建表时添加's',它应该可以工作。

create_table :library_users10s

create_table :library_books10s

它应该有用。

相关问题