我的网站上有一个博客,只有经过身份验证的用户才能发帖。如果尚未通过身份验证的现有用户在点击“创建”时正在输入评论,他将被重定向到登录视图进行身份验证,然后重定向到文章视图。我想通过呈现用户创建评论的视图来改进我的博客的功能,这样他就不必再次输入他的评论。
我对编程和红宝石相当陌生,所以我不确定如何解决这个问题。欢迎任何建议。先感谢您。
我的网站可以在https://github.com/MariusLucianPop/mariuslp-找到
下面是我认为代码的重要部分。如果您希望我更新任何内容,请告诉我。
评论控制器.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
访客控制器.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
路线.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