working form
This commit is contained in:
11
app/models/author.rb
Normal file
11
app/models/author.rb
Normal file
@@ -0,0 +1,11 @@
|
||||
class Author < ApplicationRecord
|
||||
|
||||
has_many :proverbs
|
||||
|
||||
validates :name, presence: true
|
||||
validates :unique_id, presence: true, uniqueness: true
|
||||
|
||||
def identify_uniquely
|
||||
self.unique_id = name.to_s.downcase.gsub(/[\W\s]/,'')
|
||||
end
|
||||
end
|
||||
40
app/models/proverb.rb
Normal file
40
app/models/proverb.rb
Normal file
@@ -0,0 +1,40 @@
|
||||
class Proverb < ApplicationRecord
|
||||
|
||||
belongs_to :author
|
||||
belongs_to :user
|
||||
|
||||
before_validation :setup_ownership
|
||||
|
||||
attr_writer :author_name, :user_email
|
||||
|
||||
def author_name
|
||||
author.try(:name) || @author_name
|
||||
end
|
||||
|
||||
def user_email
|
||||
user.try(:email) || @user_email
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def setup_ownership
|
||||
if author
|
||||
author.update_attributes(name: author_name)
|
||||
else
|
||||
self.author = Author.new(name: author_name)
|
||||
author.identify_uniquely
|
||||
author.save
|
||||
end
|
||||
|
||||
if user
|
||||
user.update_attributes(email: user_email.downcase)
|
||||
else
|
||||
self.user = User.create(email: user_email.downcase)
|
||||
end
|
||||
end
|
||||
|
||||
def attributes
|
||||
super.merge(author_name: author_name, user_email: user_email)
|
||||
end
|
||||
|
||||
end
|
||||
6
app/models/user.rb
Normal file
6
app/models/user.rb
Normal file
@@ -0,0 +1,6 @@
|
||||
class User < ApplicationRecord
|
||||
has_many :proverbs
|
||||
|
||||
validates :email, presence: true, uniqueness: true
|
||||
|
||||
end
|
||||
Reference in New Issue
Block a user