将块传递给Ruby中的create方法

时间:2013-07-16 12:35:50

标签: ruby-on-rails ruby

我想写一个像这个一样的方法

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

但我想保持干爽。有没有办法传递这些属性,我不知道,通过传递一个块来迭代属性数组?

2 个答案:

答案 0 :(得分:1)

您可以将一个块传递给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

您还可以将一些属性设置为第一个参数,然后传递一个块:

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

您可以在该块中实现所需的任何逻辑来分配Car属性,如下所示:

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

答案 1 :(得分:0)

请试试这个

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

请参阅https://github.com/rails/rails/blob/b15ce4a006756a0b6cacfb9593d88c9a7dfd8eb0/activerecord/lib/active_record/associations/collection_proxy.rb#L259