1. require 'rubygems'
  2. require 'sinatra'
  3. require 'sinatra/reloader'
  4. require 'sinatra/activerecord'
  5. set :database, "sqlite3:myblog.db"
  6. before do
  7. @all_posts = Post.order "created_at DESC"
  8. end
  9. class Post < ActiveRecord::Base
  10. has_many :comments # , :foreign_key => "postid"
  11. validates :username, presence: true
  12. validates :content, presence: true
  13. end
  14. class Comment < ActiveRecord::Base
  15. belongs_to :post # , :foreign_key => "postid"
  16. validates :username, presence: true
  17. validates :content, presence: true
  18. end
  19. get '/' do
  20. erb :welcome
  21. end
  22. get '/posts' do
  23. erb :posts
  24. end
  25. get '/new_post' do
  26. erb :new_post
  27. end
  28. post '/new_post' do
  29. @p = Post.new params[:type_post]
  30. if @p.save
  31. redirect to '/posts'
  32. else
  33. @error = @p.errors.full_messages.first
  34. erb :new_post
  35. end
  36. end
  37. get '/details/:id' do
  38. @details_id = params[:id]
  39. erb :details
  40. end
  41. post '/details/:id' do
  42. @details_id = params[:id]
  43. @c = Comment.new params[:type_comment] #, :post_id => "#{@details_id}"
  44. if @c.save
  45. redirect to ('/details/' + @details_id)
  46. else
  47. @error = @c.errors.full_messages.first
  48. erb :details
  49. end
  50. end
Comments powered by Disqus