Adding an owner to new records in Rails

Suppose you have a new rails site with the devise gem installed.

For example, let's say you have a tree app. You can create, edit, and delete different types of trees.

In order to create a tree, you must be logged in and you can only delete trees you've created.

You can setup a hidden field in the form that contains the current user, but there's an easier and more secure way.

If you have Devise installed and the proper association is setup you can use the current_user helper from devise.

#app/models/user.rb
has_many :trees

A user_id field must also exist in the trees table. This is setup when you run the generator. If you use the references word below, rails will automatically add the association above.

rails g model trees user:references

Then in the trees controller use this:

#app/controllers/trees_controller.rb
....
  def create
@tree = current_user.trees.new(tree_params)
  end
  ...

You'll now need to be logged in to create a new tree, but any new trees will now have an owner!

Hope this helps.