2

I have an issue with inserting data via rails command. Bellow you can see my model and the issue. The title is displaying nil even tho I created a new instance of Post with the title hash. I am aware you can do this in a different way. I am using this simple example to figure out why can't I insert or display data from the database.

Model

category.rb

class Category < ApplicationRecord
  attr_accessor :name
  has_many :posts
end

post.rb

class Post < ApplicationRecord
  attr_accessor :title, :body, :category_id, :author_id
  belongs_to :category
end

Rails c

post = Post.new(:title => 'Test')
=> #<Post id: nil, title: nil, body: nil, category_id: nil, author_id: nil, created_at: nil, updated_at: nil> 
Mahir
  • 29
  • 4
  • See the difference of `attr_accessor` (ruby level) vs `attr_accessible` (rails level) : https://stackoverflow.com/questions/3136420/difference-between-attr-accessor-and-attr-accessible – MrYoshiji Aug 15 '17 at 15:09
  • I get this error when i use attr_accessible Undefined method `attr_accessible' for # Did you mean? attr_accessor – Mahir Aug 15 '17 at 15:14
  • See first answer's comments as they explain why it is not working for Rails 4+ – MrYoshiji Aug 15 '17 at 15:16

1 Answers1

1

You should not be using the attr_accessor in your Rails class. Rails automatically make these attributes readable, and you should generally only be writing by saving records to the database.

Josh Alexy
  • 401
  • 1
  • 3
  • 13