2

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?

3
  • 2
    why do you have an initialize in a rails model? Commented Oct 4, 2022 at 18:50
  • @Haumer - Small part of larger goal. I am hoping to create attr_accessors in the initialize method based on an array that I can store elsewhere. Open to suggestions if you can think of another way to create attr_accessors based on a class or instance method. Commented Oct 4, 2022 at 18:53
  • 1
    can you give me an example? Commented Oct 4, 2022 at 18:59

2 Answers 2

0

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

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

2 Comments

Got it, thanks. I forgot about the after_initialize callback. I needed this to happen when I called .new on the object, well before any of the callbacks related to writing to the database. ( guides.rubyonrails.org/… )
"you should probably not define your own initialize method in a rails model" – any official reference for that or an explanation on why this doesn't work or isn't recommended? It seems to be a quite fundamental limitation.
0

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.

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.