Ruby-on-rails – rails constructor “def initialize” with attributes: correct way to pass in model

rubyruby-on-rails

Hi I have a model called "Listing".
Here is the constructor for the model:

def initialize(business)
    puts 'inside Listing.initialize'

    @name = business.name
    @telephone = business.telephone


    puts 'Created a new Listing'
end

I have a controller called "listings_controller"
I have is another model called "Business". Inside the "listing_controller" I have a method in which I would like to instantiate a "Listing" with attributes of a "Business".

Here is the code that does that in a "listings_controller"

def create_listings

    self.get_all  
    @businesses.each do |business|
     Listing.create(business)

    end

end


def show

   self.create_listings
   @listings = Listing.all

   respond_to do |format|
   format.html #show.html.erb
   end

end

This initialization method is not working.Im getting this exception:

wrong number of arguments (2 for 1)

Rails.root: /Users/AM/Documents/RailsWS/cmdLineWS/Businesses

Application Trace | Framework Trace | Full Trace
app/models/listing.rb:53:in initialize'
app/controllers/listings_controller.rb:18:in
block in create_listings'
app/controllers/listings_controller.rb:17:in each'
app/controllers/listings_controller.rb:17:in
create_listings'
app/controllers/listings_controller.rb:26:in `show'

How can I fix this?
Thanks

Best Answer

You could try (pseudocode/untested):

def initialize(business)
    puts 'inside Listing.initialize'

    @attributes.merge(business.attributes)

    puts 'Created a new Listing'

end
Related Topic