我跟着这个mini-tutorial successfully在我的表(汽车)中有一个列(car_code)就像一个序列(使用postgreSQL数据库)。
结果我有这张表:
CREATE TABLE Cars
(
id serial NOT NULL,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
car_date timestamp without time zone,
car_code integer DEFAULT nextval('car_code_sequence'::regclass),
CONSTRAINT cars_pkey PRIMARY KEY (id )
)
我的插入语句工作正常:
INSERT INTO cars(created_at, updated_at, car_date) VALUES (now(), now(), now());
--1|Date|Date|Date|2 <--using my car_code_sequence
不幸的是,当我在“car_controller”中调用“创建”操作时,rails应用程序会生成此语句:
INSERT INTO "cars" ("created_at", "car_code", "car_date", "updated_at")
VALUES ($1, $2, $3, $4) RETURNING "id" [
["created_at", Mon, 04 Mar 2013 14:39:55 UTC +00:00],
["car_code", nil],
["car_date", Mon, 04 Mar 2013 14:39:55 UTC +00:00],
["updated_at", Mon, 04 Mar 2013 14:39:55 UTC +00:00]]
所以,我的问题是:
我可以更改Car Model以从insert语句中排除“car_code”列(但将“car_code”保留在数据库中),即与“id”具有相同的行为。
答案 0 :(得分:1)
尝试在汽车模型中添加此代码:
class Car < ActiveRecord::Base
## --------------------- Ignore columns patch ------
@@ignore_column_pattern = /^car_code/
class << self
alias :all_columns :columns
def columns
@columns_filt ||= all_columns.reject { |col| col.name =~ @@ignore_column_pattern }
end
end
alias :all_attribute_names :attribute_names
def attribute_names
@attr_names_filt ||= all_attribute_names.reject { |att| att =~ @@ignore_column_pattern }
end
## ------------------- / Ignore columns patch ------
end