我正在创建一个连接表,大致遵循Railscast:http://railscasts.com/episodes/17-habtm-checkboxes-revised?view=asciicast
我无法在对象上设置has_many记录并收到以下错误:
2.0.0p353 :012 > invoice.fly_ids
(0.9ms) SELECT "flies".id FROM "flies" INNER JOIN "categorizations" ON "flies"."id" = "categorizations"."fly_id" WHERE "categorizations"."invoice_id" = 1
ActiveRecord::StatementInvalid: PG::Error: ERROR: operator does not exist: integer = character varying
LINE 1: ...ies" INNER JOIN "categorizations" ON "flies"."id" = "categor...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "flies".id FROM "flies" INNER JOIN "categorizations" ON "flies"."id" = "categorizations"."fly_id" WHERE "categorizations"."invoice_id" = 1
我无法让它工作,我认为这是因为'Categorizations'表使用的是varchar而不是整数。
我的迁移文件如下:
class CreateCategorizations < ActiveRecord::Migration
def change
create_table :categorizations do |t|
t.integer :user_id
t.integer :fly_id
t.timestamps
add_index :categorizations, :user_id
add_index :categorizations, :fly_id
end
end
end
但是,当我查看创建的数据库表时,:user_id和:fly_id都是varchar
为什么我在迁移文件中指定整数时会将这些字段创建为varchar?
(即使我让它工作,也可能无法解决问题......)
编辑:
用户模型:
class User < ActiveRecord::Base
....
has_many :invoices
....
end
发票型号:
class Invoice < ActiveRecord::Base
attr_accessible :active
validates :user_id, presence: true
belongs_to :user
has_many :categorizations
has_many :flies, through: :categorizations
end
发票迁移:
class CreateInvoices < ActiveRecord::Migration
def change
create_table :invoices do |t|
t.boolean :active
t.integer :user_id
t.timestamps
end
add_index :invoices, :user_id
end
end
分类模型:
class Categorization < ActiveRecord::Base
attr_accessible :fly_id, :user_id
belongs_to :invoice
belongs_to :fly
end
分类迁移:
class CreateCategorizations < ActiveRecord::Migration
def change
create_table :categorizations do |t|
t.integer :user_id
t.integer :fly_id
t.timestamps
add_index :categorizations, :user_id
add_index :categorizations, :fly_id
end
end
end
飞行模型:
class Fly < ActiveRecord::Base
attr_accessible :description, :name
validates :description, :name, presence: true
has_many :categorizations
has_many :invoices, through: :categorizations
end
飞行迁移:
class CreateFlies < ActiveRecord::Migration
def change
create_table :flies do |t|
t.string :name
t.string :description
t.timestamps
end
end
end
答案 0 :(得分:0)
<强> HABTM 强>
如果您使用的是HABTM,那么您的表格不需要任何主键(id
):
create_table :invoices_flies, :id => false do |t|
t.references :user
t.references :flies
end
has_many:通过
如果您使用has_many :through
,您的表格将使用主键,因为它将是自己的模型:
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :categorizations
has_many :flies, through: :categorizations
end
#app/models/fly.rb
Class Fly < ActiveRecord::Base
has_many :categorizations
has_many :users, through: :categorizations
end
#app/models/categorization.rb
Class Categorization < ActiveRecord::Base
belongs_to :fly
belongs_to :user
end
create_table :categorizations do |t|
t.integer :user_id
t.integer :fly_id
end
我认为您的问题可能与您的协会结构有关 - 您能否就我们如何设置它们提供一些信息?