I have the simplest possible Ruby on Rails class:
class ProductProperty < ApplicationRecord
def initialize
puts 'hello world'
end
end
But when I simply try to instantiate it, I get an ArgumentError:
[1] pry(main)> ProductProperty.new
ArgumentError: wrong number of arguments (given 1, expected 0)
I'm unclear why it thinks I am passing an argument in ("given 1
"). Do I need to do something else to be able to write an initialize
method that doesn't take arguments?
CodePudding user response:
As suggested you should probably not define your own initialize method in a rails model.
If you want to do something before, during or after you create/initalize an object you can use callbacks
For example:
class ProductProperty < ApplicationRecord
after_create :do_something_special
def do_something_special
puts "I'm doing something"
end
end
ProductProperty.create #=> "I'm doing something"
there are more callbacks available, so you can call specific methods during the lifecycle of an object.
you might also want to check out active record migrations if you want to persist and change data in your database
CodePudding user response:
You can add *args
.
class ProductProperty < ApplicationRecord
def initialize(*args)
puts 'hello world'
end
end
But I am wondering why you override initialize? You can use active record callbacks for that.