I have a blog in my website where only authenticated users can post. If an existing user that is not yet authenticated is typing a comment when he hits “create” he wil be redirected to the login view to authenticate and then redirected to the articles view. I would like to improve the functionality of my blog by rendering the view where the user was creating the comment so that he doesn’t have to type in his comment again.
I am rather new to programming and to ruby so I am not sure how to approach this problem. Any suggestions are welcomed. Thank you in advance.
My website can be found at https://github.com/MariusLucianPop/mariuslp-
Bellow are what I think are the important parts of the code. Let me know if you would like me to update anything.
comments_controller.rb
before_filter :confirm_logged_in, :only => [:create]
def create
article_id = params[:comment].delete(:article_id)
@comment = Comment.new(params[:comment])
@comment.article_id = article_id
@comment.posted_by = session[:username]
@article = Article.find(article_id)
if @comment.save
redirect_to article_path(@article)
else
render "articles/show"
end
end
protected
def confirm_logged_in
unless session[:user_id]
flash[:notice]="Please login before posting a comment."
redirect_to login_path
return false
else
return true
end
end
visitors_controller.rb
def login
#atempting to log in
authenticated_user = Visitor.authenticate(params[:username],params[:password])
if authenticated_user
session[:user_id]=authenticated_user.id
session[:username]=authenticated_user.username
flash[:notice] = "You are now logged in."
redirect_to articles_path
end
else
if !params[:username].blank? # only rendering the notice if the user tried to login at least once
flash[:notice] = "Invalid username/password combination. Please try again"
end
render "login"
end
end
routes.rb
root :to => "static_pages#index"
get "static_pages/work_in_progress"
get "categories/new"
match "work" => "static_pages#work_in_progress"
match "login" => "visitors#login" # not rest
match "logout" =>"visitors#logout" # not rest
resources :articles do
resources :comments
end
resources :tags, :taggings, :visitors, :categories
match 'contact' => 'contact#new', :as => 'contact', :via => :get
match 'contact' => 'contact#create', :as => 'contact', :via => :post
A quick approach\KIS
app / views / articles / _comment_form.html.erb