简体   繁体   中英

passing a block into create method in Ruby

I want to write a method which will work like this one

def create_new_car(salon)
    Car.create name: salon.offer.name, description: salon.offer.description, photo: salon.offer.photo, dealer_id: salon.dealer_id
end

but i want to keep it DRY. is there a way to pass those attributes by, i dont know, iterating through array of attributes by passing a block?

You can pass a block to create :

def create_new_car(salon)
    Car.create do |car|
        car.name = salon.offer.name
        car.description = salon.offer.description
        car.photo = salon.offer.photo
        car.dealer_id = salon.dealer_id
    end
end

You could also set some attributes as the first parameter and then pass a block:

    Car.create(name: salon.offer.name) do |car|
        car.description = salon.offer.description
        #...
    end

You can implement any logic you want inside that block to assign the Car properties, like this:

    attributes = ["name", "description", "photo", "dealer_id"]
    Car.create do |car|
        attributes.each { |a| car.send( "#{a}=", salon.offer.send(a) )
    end

Please try this

array_of_attrbiutes = [{name: salon.offer.name...}, {name: }, {}...]    
 def create_new_car(array_of_attributes)  
  Car.create array_of_attributes
 end  
end  

Please see https://github.com/rails/rails/blob/b15ce4a006756a0b6cacfb9593d88c9a7dfd8eb0/activerecord/lib/active_record/associations/collection_proxy.rb#L259

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM