2012-05-18 43 views
0

我在我的網站上有一個只有經過身份驗證的用戶可以發佈的博客。如果現有的尚未通過身份驗證的用戶在點擊「創建」時輸入了評論,他將被重定向到登錄視圖進行身份驗證,然後重定向到文章視圖。我想通過渲染用戶創建評論的視圖來改進我的博客的功能,以便他不必再次輸入他的評論。在登錄之後呈現視圖,其中包含估算信息登錄之前

我對編程和紅寶石很新,所以我不知道如何解決這個問題。歡迎任何建議。先謝謝你。

我的網站可以在https://github.com/MariusLucianPop/mariuslp-

婁找到是什麼,我認爲是代碼的重要組成部分。如果您希望我更新任何內容,請告訴我。

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 

回答

1

一個快速的方法\ KIS

應用程序/視圖/條/ _comment_form.html.erb

<% if confirm_logged_in %> # helper method to detect if current is logged in 

    <%= form_for [@article,@article.comments.new] do |f|%> 
    <%= f.hidden_field :article_id%> 

    <%= f.label :body %><br /> 
    <%= f.text_area :body, :cols => 50, :rows => 6 %><br /> 

    <%= f.submit%> 
    <%end%> 

<% else %> 

    <%= link_to "Login to add a comment", login_path %> 

<% end %> 
+0

感謝名單。我讓自己變得複雜。這工作很棒:) –