Rails constructor "def initialize" with attributes: the right way to pass in the model

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

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 another model called "Business". Inside the "listing_controller" I have a method in which I would like to create an instance of "Listing" with the attributes "Business".

Here is the code that does this in "lists_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 does not work. I get this exception:

 wrong number of arguments (2 for 1) 

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

Application Trace | Frame Track | 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

+4
source share
1 answer

You can try (pseudocode / unchecked):

 def initialize(business) puts 'inside Listing.initialize' @attributes.merge(business.attributes) puts 'Created a new Listing' end 
+3
source

Source: https://habr.com/ru/post/1400913/


All Articles