1

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

this lat part of your answer is pretty much what i needed, only dealer_id shouldnt be in the attributes array, because it is not to be taken from offer but from salon. anyway, thx, it was good lead
0

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

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.