我有 3 张桌子和 3 个模型:
碳水化合物
has_many :cars_domains, :dependent => :delete_all
has_many :domains, :through => :cars_domains
域名.rb
has_many :cars_domains
has_many :cars, :through => :cars_domains
和cars_domain.rb
class CarsDomain < ActiveRecord::Base
belongs_to :car
belongs_to :domain
attr_accessible :car_id, :domain_id
end
class CreateCarsDomains < ActiveRecord::Migration
def change
create_table :cars_domains, :id => false do |t|
t.references :car, :domain
t.timestamps
end
add_index :cars_domains, [:car_id, :domain_id]
end
end
一辆车可以在某些领域。当我创建汽车并绑定到域时,一切都很好。
但是当我尝试从 cars_domains 表中销毁时,出现错误:
CarsDomain.where(:car_id => 2, :domain_id => 1).destroy
ArgumentError: wrong number of arguments (0 for 1)
或者
CarsDomain.where(:car_id => 2, :domain_id => 1).destroy_all
CarsDomain Load (0.5ms) SELECT "cars_domains".* FROM "cars_domains" WHERE "cars_domains"."car_id" = 2 AND "cars_do
mains"."domain_id" = 1
(0.2ms) SAVEPOINT active_record_1
Could not log "sql.active_record" event. NoMethodError: undefined method `name' for nil:NilClass
(0.3ms) ROLLBACK TO SAVEPOINT active_record_1
ActiveRecord::StatementInvalid: PGError: ERROR: zero-length delimited identifier at or near """"
LINE 1: DELETE FROM "cars_domains" WHERE "cars_domains"."" = $1
^
: DELETE FROM "cars_domains" WHERE "cars_domains"."" = $1
from /usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.1.3/lib/active_record/connection_adapters/postgresql_
adapter.rb:1062:in `prepare'
怎么了?
升级版:
CarsDomain.destroy_all(:car_id => 2, :domain_id => 1)
CarsDomain Load (0.9ms) SELECT "cars_domains".* FROM "cars_domains" WHERE "cars_domains"."car_id" = 2 AND "cars_do mains"."domain_id" = 1 (0.2ms) SAVEPOINT active_record_1 无法记录 "sql.active_record “ 事件。NoMethodError: nil:NilClass (0.2ms) ROLLBACK TO SAVEPOINT active_record_1 ActiveRecord::StatementInvalid: PGError: 错误: 零长度分隔标识符在“””第 1 行:从“cars_domains”中删除car_domains"."" = $1 ^ : 从 "cars_domains" 中删除 "cars_domains"."" = $1
更新 2
我认为 ID 中的问题 ---- create_table :cars_domains, :id => false。因为 Destroy 方法需要它。