Model

2013-03-04 99 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