Search code examples
ruby-on-railsdevise

How to add user name to reservation in Ruby on Rails


I have created a Reservation resource. I implemented Devise so when you want to create a new reservation you have to login or create an account. What I want is that when a reservation is created, the user name of the current user is assigned to it so then I can filter reservations by username.


Solution

  • You want to use an association, check it out here: https://guides.rubyonrails.org/association_basics.html

    On your reservations table, you can add a reference to the User table via user_id, and then have a belongs_to :user

    Then you can show the username by doing reservation.user.name wherever you need.

    To add the reference, run the following: rails g migration AddUserToReservations user:references

    Which will generate the following:

    class AddUserToReservations < ActiveRecord::Migration
      def change
        add_reference :reservations, :user, index: true
      end
    end
    

    and run your migrations rails db:migrate

    Then, to assign the user to the reservation you should add a line like this in the create action of your reservations_controller.rb:

    if @reservation.save
      @reservation.user = current_user