Rails .save()不存储ID

时间:2011-03-10 07:00:50

标签: ruby-on-rails json postgresql

我在Rails中编写RESTful API,当我创建Label对象并使用.save()方法时,标签已正确保存到数据库中,但调用@label.id将返回null。

puts语句验证除id字段外的所有内容都是正确的。我还验证了数据库有正确的ID。

另外值得注意的是:这是在嵌套资源网址中: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 |

1 个答案:

答案 0 :(得分:3)

问题是您的id列不是主键,因此当数据库要求输入最后一行的id时,数据库不知道要提供哪些内容。