我在Rails中編寫了一個RESTful API,當我創建一個Label對象並使用.save()
方法時,標籤已正確保存到數據庫,但調用@label.id
返回null。Rails .save()不存儲Id
puts
語句驗證除了id字段以外的所有內容都是正確的。我也證實了數據庫有正確的ID。
另外值得注意的是:這是一個嵌套的資源URL:POST /members/:member_id/labels/
。
有沒有人遇到過這個?
def create
if params[:member_id] and params[:title]
# Periods in a username will have been translated to underscores
member_id = params[:member_id].gsub('_', '.')
title = params[:title]
# @member = Member.find(member_id) # No longer in use
@label = Label.new(:username => member_id, :title => title)
if @label.save
puts " *** label: #{@label.inspect}"
@label.reload
respond_to do |format|
format.json { render :json => @label, :status => :created and return }
end
else
respond_with :status => 406, :errors => @label.errors and return
end
end
respond_with :status => 406, :errors => [ :message => "member_id and title parameters must be provided" ] and return
end
不幸的是,問,因爲我連接到最初是通過PHP觀察現有的PostgreSQL數據庫,我不能提供一個遷移文件。但是,下面是create table
聲明以及select *
的外觀。
DROP TABLE student_labels;
CREATE TABLE student_labels (
id serial not null,
username text not null,
title text not null,
created_at timestamp not null default now(),
updated_at timestamp not null default now(),
deleted_at timestamp
);
development=> select * from student_labels; id | username | title | created_at | updated_at | deleted_at ----+----------+--------------+----------------------------+----------------------------+------------ 7 | F0003 | Boom | 2011-03-10 05:49:06.01771 | 2011-03-10 05:49:06.01771 | 8 | F0003 | Boom | 2011-03-10 05:49:28.659 | 2011-03-10 05:49:28.659 | 9 | F0003 | Boom | 2011-03-10 05:52:03.343815 | 2011-03-10 05:52:03.343815 | 10 | F0003 | Boom | 2011-03-10 05:53:07.803489 | 2011-03-10 05:53:07.803489 |
在你的投入中,你的意思是使用'「標籤:#{@ label.inspect}」'?因爲從我看到的非實例變量'label'不存在? – nzifnab 2011-03-10 07:04:38
我認爲@ label.reload不是必需的。檢查你的數據庫條目。是的,你的puts語句有'label'不存在。 – Ashish 2011-03-10 07:09:15
你可以向我們展示標籤表的遷移嗎? – Chirantan 2011-03-10 09:09:02