Topher Fangio
Topher Fangio

Reputation: 20667

Rails .save() Doesn't Store Id

I'm writing a RESTful API in Rails and when I create a Label object and use the .save() method, the label is properly saved to the database but calling @label.id returns null.

The puts statement verifies that everything is correct except the id field. I have also verified that the database has the proper ids.

Also of note: this is inside of a nested resource URL: POST /members/:member_id/labels/.

Has anyone experienced this before?

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

Unfortunately, I cannot provide a migration file as asked since I am connecting to an existing PostgreSQL database originally viewed through PHP. However, below is the create table statement along with what a select * looks like.

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 |

Upvotes: 0

Views: 557

Answers (1)

Samuel
Samuel

Reputation: 38346

The problem is that your id column isn't a primary key so the database doesn't know what to give rails when it asks for the id of the last inserted row.

Upvotes: 3

Related Questions