Mahir
Mahir

Reputation: 29

Issue with inserting data into database via rails command

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> 

Upvotes: 2

Views: 54

Answers (1)

Josh Alexy
Josh Alexy

Reputation: 411

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.

Upvotes: 1

Related Questions