2016-01-13 214 views
2

試圖學習RoR。目前正在向用戶添加評論。到目前爲止,我有一個帖子模型,評論模型和post_comments模型(將兩者關聯起來)。所以對於 '軌控制檯' 我可以運行:(比如我設置P = Post.first和c = Comment.first)Ruby on Rails - 添加評論

p.comments < <Ç

這形成了這樣的關聯它在控制檯中工作。我似乎無法從用戶界面中獲得評論來形成此關聯。到目前爲止,我在「comments/new」創建註釋(不確定這是否是問題,是否需要在「post」的「show view」中創建)。

下面是一些代碼片段

控制器 comments_controller.rb

class CommentsController < ApplicationController 

def index 
    @comment = Comment.all 
end 

def new 
    @comment = Comment.new 
end 

def create 
    @comment = Comment.new(commentParams) 
    if @comment.save 
    flash[:success] = "Comment successfully added" 
    redirect_to comments_path(@comment) 
    else 
    render 'new' 
    end 
end 

def show 
    @comment = Comment.find(params[:id]) 
end 

private 

    def commentParams 
    params.require(:comment).permit(:comment) 
    end 
end 

posts_controller

class PostsController < ApplicationController 
before_action :setPost, only: [:edit, :update, :show, :destroy, :sold] 
before_action :requireUser, except: [:index, :show] 
before_action :requireSameUser, only: [:edit, :update, :destroy, :sold] 

def index 
    @posts = Post.paginate(page: params[:page], per_page: 20) 
end 

def new 
    @post = Post.new 
end 

def create 
    @post = Post.new(postParams) 
    @post.user = currentUser 
    if @post.save 
    flash[:success] = "Post successfully added." 
    redirect_to post_path(@post) 
    else 
    render 'new' 
    end 
end 

def update 
    if @post.update(postParams) 
    flash[:success] = "Post successfully updated." 
    redirect_to post_path(@post) 
    else 
    render 'edit' 
    end 
end 

def show 
end 

def edit 
end 

def sold 
    @post.toggle(:sold) 
    @post.save 
    redirect_to post_path(@post) 
end 

def destroy 
    @post.destroy 
    flash[:danger] = "Item successfully deleted." 
    redirect_to posts_path 
end 

private 
    def postParams 
    params.require(:post).permit(:title, :price, :description, category_ids:[]) 
    end 

    def setPost 
    @post = Post.find(params[:id]) 
    end 

    def requireSameUser 
    if currentUser != @post.user and !currentUser.admin 
     flash[:danger] = "You can only edit or delete your own items" 
     redirect_to root_path 
    end 
    end 
end 

模型 comment.rb

class Comment < ActiveRecord::Base 
    belongs_to :post_comments 
    belongs_to :user 
    belongs_to :post 
end 

post_comment.rb

class PostComment < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :comment 
end 

post.rb

class Post < ActiveRecord::Base 
    belongs_to :user 
    has_many :post_categories 
    has_many :categories, through: :post_categories 
    has_many :post_comments 
    has_many :comments, through: :post_comments 

    validates :title, presence: true, 
       length: { minimum: 4, maximum: 20 } 

    validates :description, presence: true, 
         length: { maximum: 1000 } 
    validates :user_id, presence: true 

瀏覽 帖/ show.html.erb

<p>Comments: <%= render @post.comments %></p> 

這使得下面

評論/ _comment.html.erb <%的部分= link_to comment.name,comment_path(評論)%>  

最後是新的評論頁面,因爲它是。

的意見/ new.html.erb

<h1>New Comment</h1> 

<%= render 'shared/errors', obj: @comment %> 

<div class="row"> 
<div class="col-xs-12"> 
    <%= form_for(@comment, :html => {class: "form-horizontal", role: "form"}) do |f| %> 

    <div class="form-group"> 
    <div class="control-label col-sm-2"> 
     <%= f.label :comment %> 
    </div> 

    <div class="col-sm-8"> 
     <%= f.text_area :comment, rows: 3, class: "form-control", placeholder: "Please enter a comment", autofocus: true %> 
    </div> 
    </div> 

    <div class="form-group"> 
    <div class="center col-sm-offset-1 col-sm-10"> 
     <%= f.submit class: "btn btn-primary btn-lg" %> 
    </div> 
    </div> 
<% end %> 

任何幫助將大大收到。

更新

登錄

Started GET "/posts/2" for ::1 at 2016-01-15 12:39:55 +0000 
Processing by PostsController#show as HTML 
Parameters: {"id"=>"2"} 
[1m[36mPost Load (0.1ms)[0m [1mSELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1[0m [["id", 2]] 
[1m[35mUser Load (0.1ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] 
[1m[36m (0.1ms)[0m [1mSELECT COUNT(*) FROM "posts" WHERE "posts"."user_id" = ?[0m [["user_id", 1]] 
[1m[35mCategory Exists (0.1ms)[0m SELECT 1 AS one FROM "categories" INNER JOIN "post_categories" ON "categories"."id" = "post_categories"."category_id" WHERE "post_categories"."post_id" = ? LIMIT 1 [["post_id", 2]] 
[1m[36mCategory Load (0.0ms)[0m [1mSELECT "categories".* FROM "categories" INNER JOIN "post_categories" ON "categories"."id" = "post_categories"."category_id" WHERE "post_categories"."post_id" = ?[0m [["post_id", 2]] 
Rendered categories/_category.html.erb (0.2ms) 
[1m[35mComment Load (0.1ms)[0m SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ? [["post_id", 2]] 
Rendered comments/_comment.html.erb (0.1ms) 
Rendered posts/show.html.erb within layouts/application (6.5ms) 
[1m[36mCategory Load (0.1ms)[0m [1mSELECT "categories".* FROM "categories"[0m 
Rendered layouts/_navigation.html.erb (0.9ms) 
Rendered layouts/_messages.html.erb (0.1ms) 
Rendered layouts/_footer.html.erb (0.1ms) 
Completed 200 OK in 52ms (Views: 50.3ms | ActiveRecord: 0.5ms) 
+0

我認爲問題在於,您的'新評論'視圖中沒有任何地方提及該帖子,因此當您創建評論時,它不會附加到帖子中。這就是說我不明白你爲什麼使用post_comments關聯表,如果評論只屬於一個你不需要的帖子。 – taglia

+0

感謝您的回覆。是的,這對我有意義。同樣在後面的觀察,最好是添加一列到帖子數據庫的一系列評論? @taglia –

+0

我只是在你的評論表中添加一個post_id列,所以評論屬於帖子,帖子會有很多評論。 – taglia

回答

5

作爲註釋可以屬於一個帖子而已,你並不需要一個關聯表(post_comments)。你只需要一個簡單的一對多關係。

您發表的留言是:

class Post < ActiveRecord::Base 
    has_many :comments 
    ... 
end 

和評論會是這樣的:

class Comment < ActiveRecord::Base 
    belongs_to :post 
    ... 
end 

只要確保你在comments表的必要post_id列(您可以檢查db/schema.rb文件)。如果丟失,您可以使用下面的遷移,將其添加:

class AddPostIdToComments < ActiveRecord::Migration 
    def change 
    add_column :comments, :post_id, :integer 
    add_index :comments, :post_id 
    end 
end 

您還需要確保你保持某處參考後,每當用戶嘗試創建一個信息的評論中。您可以將其添加到您的comments/new.html.erb模板的隱藏字段中。您可以在通過URL傳遞後在PostsController中設置new操作中的隱藏字段。

所以,在你posts/show.html.erb模板中,您將有:

<%= link_to "Add Comment", new_comment_path(post_id: @post.id) %> 

在你new行動,PostsController

def new 
    @comment = Comment.new(post_id: params[:post_id]) 
end 

最後,在表單中的隱藏字段將是:

<%= f.hidden_field :post_id %> 

最後,將post_id參數添加到li st允許的參數CommentsController

+0

這看起來不錯。我將執行這些更改並返回結果。再次非常感謝。 –

+0

嘿,我已經實現了所有這些變化,它已經全部建立起來了。唯一的是當我創建一個新的評論並檢查控制檯時,post_id被設置爲零。不知道如何讓它看起來對我來說都是正確的。 @taglia –

+1

當你點擊「新評論」按鈕時,該URL看起來像是「http://your.server.com/comments/new?post_id = 123'?您是否已將'post_id'添加到CommentsController中允許的參數列表中?它應該是'params.require(:comment).permit(:comment,:post_id)'。 – taglia