0

simple question. I'm trying to create a new object for a very basic class

class Article < ActiveRecord::Base
  attr_accessor :title, :content

  validates :title,  :presence => true
  validates :content, :presence => true
end

However, when I try to create a new object in the console, the title and content fields always show up as nil

1.9.2-head :021 > a = Article.new(title: "abcdefg", content: "hijklmnop")
 => #<Article id: nil, title: nil, content: nil, created_at: nil, updated_at: nil> 

Why can't I create a new object?

1
  • Try with Article.create!(title: "abcdefg", content: "hijklmnop") . The ! will display errors as to why the creating that object failed Commented Mar 12, 2012 at 5:31

1 Answer 1

2

Were you trying to use attr_accessible?

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

3 Comments

@Jazear By using attr_accessor instead of attr_accessible you are over-riding the default rails setter/getter and hence the value you are setting in the constructor is ignored.
Correct, thanks. I guess now I need to create specific setter methods if I want to change the content of these objects
Or better, delete the call to attr_accessor and use the generated setters and getters unless you have reason to do otherwise.

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.