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> 
3
  • See the difference of attr_accessor (ruby level) vs attr_accessible (rails level) : stackoverflow.com/questions/3136420/… Commented Aug 15, 2017 at 15:09
  • I get this error when i use attr_accessible Undefined method `attr_accessible' for #<Class:0x0000000cd719f8> Did you mean? attr_accessor Commented Aug 15, 2017 at 15:14
  • See first answer's comments as they explain why it is not working for Rails 4+ Commented Aug 15, 2017 at 15:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.