allegutta
allegutta

Reputation: 5644

Rails with Devise: Problems with associations

I have made new Rails app. It is totally fresh with just one User model (that is generated through Devise) and a Post model that is generated with scaffold. In the Post model I have a column in the database that is named user_id.

The problem is that user_id in the Post table always is nil (it won't change to the user_id of the user that is posting). I suspect that is has something to do with Devise, but I'm not totally sure. Any suggestions on what to do?

user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_many :posts, dependent: :destroy
end

post.rb

class Post < ActiveRecord::Base
  attr_accessible :title, :user_id
  belongs_to :user
end

gemfile

source 'https://rubygems.org'

gem 'rails', '3.2.13'
gem 'bootstrap-sass', '2.1'
gem 'devise'

group :development do
  gem 'sqlite3', '1.3.5'
end

group :assets do
  gem 'sass-rails',   '3.2.5'
  gem 'coffee-rails', '3.2.2'

  gem 'uglifier', '1.2.3'
end

gem 'jquery-rails', '2.0.2'

group :production do
    gem 'pg', '0.12.2'
end

gem 'will_paginate', '> 3.0'

post_controller (create)

  def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

Upvotes: 1

Views: 1619

Answers (1)

Jason Swett
Jason Swett

Reputation: 45084

I'm guessing the user_id attribute isn't getting set because you're not setting it. :)

  def create
    @post = Post.new(params[:post])
    @post.user_id = current_user.id # You need to add this line

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

Side note: I would recommend putting a not-null constraint on post.user_id as well as (if you haven't already) a foreign key constraint from post.user_id to user.id. Those constraints help to both prevent and more easily diagnose these kinds of problems.

Upvotes: 3

Related Questions