Model

2013-03-04 100 views
0

上的Rails序列列我跟着这个mini-tutorial successfully在我的表(汽车)中有一列(car_code)像序列(使用postgreSQL数据库)一样工作。Model

至于结果,我有这个表:

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_code”保留在数据库中),即与“id”具有相同行为来更改Car Model以排除“car_code”列。

回答

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 

来源:https://stackoverflow.com/a/10319903/1042324