Question: I would like to get the id of an object after creating it, like so:

```
 post = Post.create_with_data(data)
 post_id = post.id #id of the post object just created in previous line

```

However, post\_id is `nil`. How do I achieve my goal? I don't want to use `Post.last`, because it might create data conflict when multiple users trying to create post at the same time.

Thank you.

Answer: 
Rails functions return the last evaluated statement. If you're going to write your own `create_with_data` model method, you'll want to return the actual object. `object.save` with return either `true` or `false`, but not the object itself. 

In order to return the object (and thus access its id in the manner specified), just express the object itself as the last statement of your function and it will automatically be returned when you call the method. 

```
class Post < ActiveRecord::Base

  def self.create_with_data(data)
    photo = self.new(data)
    photo.save
    photo # returns the photo object
  end

end

```
```
class Post < ActiveRecord::Base
  ...
  def data=(data)
    # ... use data here
  end
end

Post.create(data: data)

```

It's much cleaner and it will call save for you! Your error is because create\_with\_data is not persisting the object (not saving, failing a validation when saving, etc.)