Skip to content

Commit

Permalink
Add relation between courses and user
Browse files Browse the repository at this point in the history
  • Loading branch information
dalvarez2596 committed Oct 12, 2024
1 parent 1873239 commit 811e71d
Show file tree
Hide file tree
Showing 7 changed files with 23 additions and 2 deletions.
1 change: 1 addition & 0 deletions app/controllers/courses_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def edit
# POST /courses or /courses.json
def create
@course = Course.new(course_params)
@course.user = current_user

respond_to do |format|
if @course.save
Expand Down
1 change: 1 addition & 0 deletions app/models/course.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ class Course < ApplicationRecord
validates :title, presence: true
validates :description, presence: true, length: { minimum: 5 }

belongs_to :user
def to_s
title
end
Expand Down
6 changes: 6 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,10 @@ class User < ApplicationRecord
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable

def to_s
email
end

has_many :courses
end
2 changes: 2 additions & 0 deletions app/views/courses/index.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
%tr
%th Title
%th Description
%th User
%th
%th
%th
Expand All @@ -16,6 +17,7 @@
%tr
%td= course.title
%td= course.description
%td= course.user
%td= link_to 'Show', course
%td= link_to 'Edit', edit_course_path(course)
%td= link_to 'Destroy', course, method: :delete, data: { confirm: 'Are you sure?' }
Expand Down
5 changes: 5 additions & 0 deletions db/migrate/20241012032156_add_user_to_courses.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class AddUserToCourses < ActiveRecord::Migration[7.2]
def change
add_reference :courses, :user, null: false, foreign_key: true
end
end
5 changes: 4 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion db/seeds.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
User.create!(email: 'admin@admin.com', password: 'Password1234', password_confirmation: 'Password1234')

30.times do
Course.create!([ {
title: Faker::Educator.course_name,
description: Faker::TvShows::GameOfThrones.quote
description: Faker::TvShows::GameOfThrones.quote,
user_id: User.first.id
} ])
end

0 comments on commit 811e71d

Please sign in to comment.