簡體   English   中英

在Ruby中將一個塊傳遞給create方法

[英]passing a block into create method in 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

但我想保持干燥。 我不知道有沒有辦法通過傳遞一個塊來遍歷屬性數組來傳遞那些屬性?

您可以傳遞一個塊來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

請嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM