2016-03-02 15 views
0

比方說,我有一個具有很多屬性的Rails模型,並且我想要複製其中的大部分或全部,而不復制只是ID和前幾個字段。無需手動輸入所有字段名稱來複制屬性散列,而是通過什麼方式來完成此操作?如何通過索引分割紅寶石中的散列? Rails模型之間的用例複製屬性

+2

通過提供一個小例子並顯示期望的返回值,可以改進此問題。也許從你的答案中拉出你的例子,並編輯你的答案來參考問題中的例子。 –

+3

請閱讀「[問]」和「[mcve]」。爲我們提供一個例子或更好的描述。 –

回答

0

將散列轉換爲數組,選擇索引,轉換回散列。在這個例子中,我想複製所有從model_1的屬性model_2從索引4.顯然model_1和model_2必須爲同一型號

hash = model_1.attributes 

model_2.attributes = hash.to_a[4..-1].to_h 

當然,我們也可以做到這

model_1.attributes = model_2.attributes.to_a[4..-1].to_h 
+1

你可以使用'-1'索引來代替'hash.length':'model_2.attributes = hash.to_a [4 ..- 1] .to_h' – Ilya

+0

我相信你想要'[4..hash_length-1]'或者'[4 ... hash_length]'(後一種情況下是三個點)。你也可以編寫'[4,hash_length-4]',但是[4,-1]'當然是最好的。 –

+0

'''[4 ..- 1]'''簡潔。喜歡! – lacostenycoder

2

您可以指定所有屬性你不使用except方法要

model_2.attributes.except(:id, :other_attribute, :and_another) 
+0

或'slice'指定想要使用的所有屬性 – Ilya

+0

考慮將其更改爲'model_2.attributes.except(* model_2.attributes.keys.first(n))'。 –

+0

我知道除了方法,但是避免必須鍵入屬性的名稱,因爲我很懶,不在乎這些名字在這種情況下;) – lacostenycoder

2

您可以使用selectwith_index方法你的目標:

model_2.attributes = model_1.attributes.select.with_index { |_, i| i >= 4 } 

在這種情況下,你可以指定任何屬性位置間隔。

+1

讀者被提醒,這是[Hash#select](http ://ruby-doc.org/core-2.2.0/Hash.html#method-i-select),而不是[Enumerable#select](http://ruby-doc.org/core-2.2.0/Enumerable html的#方法-i的選擇)。 –

+0

我認爲你的意思是在作業左側的model_2.attributes,但是這個工作得很好。 – lacostenycoder