Setting attribute in constructor, .NEW works but not .CREATE

I have table “decks” with three fields: “id”, “created_at” and “cards”
which is a 264-character string field. I have modified the model with a
constructor, as follows:

class Deck < ActiveRecord::Base
attr_reader :cards
def initialize
@cards = “12345”
end
end

If I call Deck.new from my controller, I get no errors and an object
with the “cards” attribute set appropriately to “12345”. This object can
be saved without error by calling the .save method. However, if I call
Deck.create (in order to create and save in one fell swoop), then I get
an error, shown below. If I take out the constructor method, Deck.create
works just fine.

I’d appreciate any assistance.
thanks.
yb

ArgumentError in PokerController#index
wrong number of arguments (1 for 0)
RAILS_ROOT: ./script/…/config/…
Application Trace | Framework Trace | Full Trace
c:/server/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/base.rb:406:in
initialize' c:/server/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/base.rb:406:innew’
c:/server/ruby/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib/active_record/base.rb:406:in
create' #{RAILS_ROOT}/app/controllers/poker_controller.rb:3:inindex’

try changing your initialize method…

def initialize( *args )
super
@cards = “12345”
end

This will allow Deck.new calls which have arguments, whiche active
record
expects all objects to allow.

mark

Excellent! That is getting me past the error and getting my row into the
database with a call to Deck.create.

However…

In the database row that is created, the “cards” column is blank. In the
controller/view, after calling Deck.create, the “cards” attribute is
populated with “12345” as expected, it’s just not making it into the db.

So - the database save is happening before my constructor populates the
attribute (or something)?

???

Thanks so much for you help, Mark.

c.

The reason for this is because you are not using the cards attribute
from
the database. You have your class defined like so…

class Deck < ActiveRecord::Base
attr_reader :cards
def initialize( *args )
super
@cards = “12345”
end
end

If the Deck table has a cards column, you should define your class like
so…

class Deck < ActiveRecord::Base
def initialize( *args )
super
self.cards = “12345”
end
end

Rails will automatically create the methods Deck#cards and Deck#cards=.
When
you do attr_reader, you are overwriting the Deck#cards method to return
the
instance variable @cards. This never sets the actual variable which
active
record uses to store in the db.

hope that helps,

mark

Like a charm!!!

Sorry - took a dinner break, put the kids to bed, etc. Just got back and
implemented according to your help and everything is working perfectly.

Again - many thanks.
c.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs