2017-02-17 126 views
0

我正在嘗試添加用戶添加評論到我的rails站點上的帖子的能力。我如何評論我的帖子?

我在我的數據庫中有一個Posts表和一個Users表。我正在使用足智多謀的路線在我的帖子控制器的'show'動作上顯示各個帖子。我希望能夠在帖子下方顯示評論框,以便用戶輸入評論,然後點擊提交併讓它創建評論。

我試着做一個評論模型,給他們一個belongs_to關係的用戶和帖子。我還將has_many關係添加到用戶和發佈模型。然後,我嘗試讓評論控制器使用「創建」操作來處理每個帖子「顯示」操作的表單。

我遇到了無法獲取post_id以注入新評論的問題。我可以通過從用戶會話中獲取user_id來獲取user_id,但傳遞給評論控制器上的「創建」操作的唯一內容就是通過表單評論的實際文本。

這是添加此功能的好方法嗎?必須有更好的做法,或者我只是想念一些東西。

我的帖子控制器「秀」行動:

#PostsController.rb 

def show 
    @post = Post.where(:id => params[:id]).first 
    if @post.nil? 
    flash[:error] = "Post does not exist" 
    redirect_to(root_path) 
    end 
    @comment = Comment.new 
end 

在「顯示」視圖的形式在PostsController「顯示」行動:

#views/posts/show.html.erb 

<%= form_for @comment do |f| %> 
    <%= f.text_area(:content, :size => '20x10', :class => 'textarea') %> 
    <%= f.submit('Create Post', class: 'button button-primary') %> 
<% end %> 

我的意見控制器「創建」行動:

#CommentsController.rb 

def create 
    @comment = Comment.new(params.require(:comment).permit(:content, :post_id, :user_id)) 
    @comment.user_id = session[:user_id] 
    #Need to set post_id here somehow 
    if @comment.valid? 
    @comment.save 
    flash[:success] = "Comment added successfully." 
    redirect_to(post_path(@comment.post)) 
    else 
    @error = @comment.errors.full_messages.to_s 
    @error.delete! '[]' 
    flash.now[:error] = @error 
    render('posts/show') 
    end 
end 

我的Post模型:

class Post < ApplicationRecord 
    belongs_to :subject 
    belongs_to :user 
    has_many :comments 

    validates :title, :presence => true, 
        :length => {:within => 4..75} 


    validates :content, :presence => true, 
         :length => {:within => 20..1000} 
end 

我的評論模式:

class Comment < ApplicationRecord 
    belongs_to :user 
    belongs_to :post 

    validates :content, :presence => true, 
         :length => {:within => 6..200} 

end 
+0

您是否正在學習任何教程?請更新您的問題與帖子和評論模型 – Hizqeel

+0

你到達那裏,這並不難,嘗試深入挖掘在線資源,你會發現它很容易。順便說一句,'@post = Post.where(:id => params [:id])。first' >>>>你可以使用'.find'與ID,[.find](http:// apidock。 com/rails/ActiveRecord/FinderMethods/find) – tkhuynh

+0

@Hizqeel我在Lynda上使用了一個關於我的初始應用程序創建的教程,但是我無法在線找到有關如何添加註釋的資源。我爲我的模型添加了代碼。 – Kecoey

回答

1

在您的文章控制器表演動作,使新的評論屬於後

def show 
    @post = Post.where(:id => params[:id]).first 
    if @post.nil? 
    flash[:error] = "Post does not exist" 
    redirect_to(root_path) 
    end 
    @comment = @post.comments.new # <--- here's the change 
end 

然後POST_ID字段添加到窗體作爲隱藏字段

<%= form_for @comment do |f| %> 
    <%= f.hidden_field :post_id %> 
    <%= f.text_area(:content, :size => '20x10', :class => 'textarea') %> 
    <%= f.submit('Create Post', class: 'button button-primary') %> 
<% end %> 

而且你應該不用改變評論cont滾筒創建動作

+0

只需檢查並確保它工作。看起來像它!謝謝!雖然我對控制器演出中的新行感到有點困惑。我不確定它爲什麼有效,只是用「@comment = Comment.new」發表新評論不會 – Kecoey

+0

'@comment = @ post.comments.new'與'@comment = Comment.new (post_id:@ post.id)'。您只需要爲註釋設置post_id,然後確保表單保留了它。 – TerryS