I have a nested resource with 'posts' containing many 'comments' and associations set up between these models. But when I create a comment for a post the 'post_id' in the comments table remains empty and no link is established. The comment text itself gets created ok.
I'm using Rails ver 4.2.1 and a postgresql database.
The associations are set up like this:
class Comment < ActiveRecord::Base belongs_to :post end class Post < ActiveRecord::Base has_many :comments, dependent: :destroy end This is the route set up:
resources :posts do resources :comments end
I create the comments from the comments/new view with this code:
= form_for [@post, @comment] do |f| = f.label :comment = f.text_field :comment = f.submit "Add Comment" My comments controller is like this:
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 I have the column 'post_id' set up in the comments table and my schema is this:
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 Just can't work out what is going on, I've used almost identical code on another project and that worked.
Any help would be great.