aru
aru

Reputation: 1

content gets saved as nil rails

I have run into a rather unusual situation and I can't seem to figure out why this is happening:

I have a User model:

class User < ActiveRecord::Base
  has_many :posts, dependent: :destroy
end

And a Post model:

class Post < ActiveRecord::Base
  attr_accessor :content
  belongs_to :user
  default_scope{order('created_at DESC')}

  #validations
  validates(:content, presence: true, length: {maximum: 140})
  validates(:user_id, presence: true)
end

My migration for posts looks like this:

require_relative '20150405091935_create_posts'
class FixPosts < ActiveRecord::Migration
  def change
    revert CreatePosts #this was the original migration w/o a user reference

    create_table :posts do |t|
      t.belongs_to :user, index: true
      t.string :content
      t.integer :user_id

      t.timestamps null: false
    end
  end
end

The issue

I create a post

user = User.first
user.posts.create(content: "This is a post.")
=> true

However when I print it out I get the following:

#<Post:0x007fc1a0f1d628
  id: 1,
  user_id: 1,
  content: nil,
  created_at: Sun, 19 Apr 2015 19:45:38 UTC +00:00,
  updated_at: Sun, 19 Apr 2015 19:45:38 UTC +00:00>]

The content is lost and returns a nil.

What is going on here? Am I missing something?

Any help will be appreciated!Thank you for your time.

Please let me know if any additional info is required. You can also see the entire code base on GitHub.

Upvotes: 0

Views: 58

Answers (1)

potashin
potashin

Reputation: 44581

You should remove attr_accessor :content from your Post model as it sets content as virtual attribute – model attribute that is not persisted to the database .

Upvotes: 1

Related Questions