From d40c681d2f9d56e01cd5f1ff3e586b79ea4397f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Ankarstro=CC=88m?= Date: Wed, 3 Mar 2021 14:32:43 +0100 Subject: Add 'user' model --- interfaces/ruby/models/comment.rb | 18 +++++++++++++----- interfaces/ruby/models/post.rb | 2 ++ interfaces/ruby/models/user.rb | 17 +++++++++++++++++ interfaces/ruby/ruby.rb | 1 + 4 files changed, 33 insertions(+), 5 deletions(-) create mode 100644 interfaces/ruby/models/user.rb (limited to 'interfaces') diff --git a/interfaces/ruby/models/comment.rb b/interfaces/ruby/models/comment.rb index b3977f6..f7f9e13 100644 --- a/interfaces/ruby/models/comment.rb +++ b/interfaces/ruby/models/comment.rb @@ -1,18 +1,26 @@ class Comment < ActiveRecord::Base belongs_to :post + belongs_to :user, optional: true + validates_presence_of :date - validates_presence_of :author - validates_presence_of :email validates_format_of :email, with: /@/ validates_presence_of :body + validate :user_or_guest + +private + + def user_or_guest + user.present? or (author.present? and email.present?) + end end class CreateCommentTable < ActiveRecord::Migration[6.0] def change create_table :comments do |t| - t.references :post, foreign_key: true, index: true - t.string :author, null: false - t.string :email, null: false + t.references :post, foreign_key: true, index: true, null: false + t.references :user, foreign_key: true + t.string :author + t.string :email t.string :body, null: false t.timestamps end diff --git a/interfaces/ruby/models/post.rb b/interfaces/ruby/models/post.rb index e952aed..3a29a1c 100644 --- a/interfaces/ruby/models/post.rb +++ b/interfaces/ruby/models/post.rb @@ -1,4 +1,5 @@ class Post < ActiveRecord::Base + belongs_to :user has_many :comments has_many :tags, through: :post_tag_links @@ -10,6 +11,7 @@ end class CreatePostTable < ActiveRecord::Migration[6.0] def change create_table :posts do |t| + t.references :user, foreign_key: true, null: false t.string :slug, null: false, unique: true, index: true t.string :title, null: false t.string :body, null: false diff --git a/interfaces/ruby/models/user.rb b/interfaces/ruby/models/user.rb new file mode 100644 index 0000000..8b88b4a --- /dev/null +++ b/interfaces/ruby/models/user.rb @@ -0,0 +1,17 @@ +class User < ActiveRecord::Base + has_many :posts + + validates_presence_of :username + validates_presence_of :password_hash +end + +class CreateUserTable < ActiveRecord::Migration[6.0] + def change + create_table :users do |t| + t.string :name + t.string :username, null: false, unique: true, index: true + t.string :password_hash, null: false + t.timestamps + end + end +end diff --git a/interfaces/ruby/ruby.rb b/interfaces/ruby/ruby.rb index d5c0e9c..2e6c5d9 100644 --- a/interfaces/ruby/ruby.rb +++ b/interfaces/ruby/ruby.rb @@ -9,3 +9,4 @@ require_relative 'models/comment' require_relative 'models/config' require_relative 'models/post' require_relative 'models/tag' +require_relative 'models/user' -- cgit v1.2.3