2015-04-04 64 views
0

我有一個嵌套的資源'posts'包​​含許多'評論'和這些模型之間建立的關聯。但是,當我爲帖子創建評論時,評論表中的「post_id」保持空白,並且沒有建立鏈接。評論文本本身被創建好。活動記錄belongs_to協會不添加外鍵

我正在使用Rails版本4.2.1和postgresql數據庫。

該協會正在建立這樣的:

class Comment < ActiveRecord::Base 
    belongs_to :post 
end 

class Post < ActiveRecord::Base 
    has_many :comments, dependent: :destroy 
end 

這是建立路由:

我創建了評論意見 結束:

資源:帖子做 資源此代碼的評論/新視圖:

= form_for [@post, @comment] do |f| 
    = f.label :comment 
    = f.text_field :comment 
    = f.submit "Add Comment" 

我的評論控制器是這樣的:

class CommentsController < ApplicationController 

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

    def create 
    @post = Post.find(params[:post_id]) 
    @comment = Comment.create(comment_params) 
    redirect_to posts_path 
    end 

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

end 

我有列「POST_ID」在評論表設置和我的模式是這樣的:

ActiveRecord::Schema.define(version: 20150404204033) do 

    # These are extensions that must be enabled in order to support this database 
    enable_extension "plpgsql" 

    create_table "comments", force: :cascade do |t| 
    t.string "comment" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.integer "post_id" 
    end 

    add_index "comments", ["post_id"], name: "index_comments_on_post_id", using: :btree 

    create_table "posts", force: :cascade do |t| 
    t.string "name" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    add_foreign_key "comments", "posts" 
end 

就不能工作是什麼繼續,我在另一個項目上使用了幾乎相同的代碼,並且工作。

任何幫助將是偉大的。

回答

1

在此代碼:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = Comment.create(comment_params) 
    redirect_to posts_path 
end 

找到職位,但從來沒有用它做任何事情。該評論不知道該帖子。您需要將評論的帖子設置爲@post