Skip to content

Instantly share code, notes, and snippets.

@isorsa
Created September 7, 2022 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isorsa/f6431daf60fd42245a9c03f1b6167029 to your computer and use it in GitHub Desktop.
Save isorsa/f6431daf60fd42245a9c03f1b6167029 to your computer and use it in GitHub Desktop.
Ruby/Rails Challenge
require 'csv'
class User < ApplicationRecord
has_many :posts
has_many :comments
end
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
has_many :comments, class_name: "Comment", foreign_key: :post_id
end
class Post < ApplicationRecord
has_many :comments
belongs_to :user
def self.import(file_name)
new_file = "#{DateTime.now.to_i}_#{file_name}"
CSV.open(new_file, headers: true) do |csv|
CSV.foreach(Rails.root.join(file_name)) do |row|
data = {
title: row[0],
body: row[1],
author: row[2],
email: row[3]
}
if !Post.where(title: data[:title]).present?
if User.all.select { |user| user.name == data[:author] }.first.present?
Post.create!(title: data[:title], user: User.where(name: data[:author]).first, body: data[:body])
else
user = User.create!(name: data[:author])
Post.create!(title: data[:title], user: user, body: data[:body])
end
else
post = Post.where(user: data[:author], title: data[:title], body: data[:body]).first
user = User.where(name: data[:author]).first
if !post
if user
Post.create!(title: data[:title], user: User.where(name: data[:author]).first, body: data[:body])
else
user = User.create(name: data[:author])
Post.create!(title: data[:title], user: user, body: data[:body])
end
end
end
data[:comments_count] = count_comments(post)
csv << data
end
end
end
def count_comments(post)
count = post.comments.count
post.comments.each { |comment| count += count_comments(comment) }
count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment