2017-04-25 37 views
1
訪問關聯

我創建了一個自定義驗證器,以驗證我的has_many關聯中的某些屬性。在validates_with

我的類:

class User < ApplicationRecord  
    has_many :addresses 
    accepts_nested_attributes_for :addresses, allow_destroy: true 

    validates_with UniquenessMemoryValidator, 
       attributes: [:name], 
       collection: :addresses, 
       message: 'My custom message' 
end 

UniquenessMemoryValidator:

class UniquenessMemoryValidator < ActiveModel::Validator 
    def validate(record) 
    attrs, message = options.values_at(:attributes, :message) 
    collection = record[options[:collection]] 
    puts "collection #{collection}" # it's nil 
    end 
end 

的問題是,當我嘗試訪問我協會(在這種情況下:地址),它打印零。

所以我的問題是:如何在驗證器中訪問我的「嵌套」數組? PS:我可以訪問我的「記錄」的任何其他屬性,而不是關聯。

回答

1

您可以send嘗試,如果想要動態做,因爲這是通常的方法調用:

collection = record.send(options[:collection]) 

此外,您可以訪問到嵌套數組只有accepts_nested_attributes_for驗證與reject_if。 在reject_if你可以通過方法

accepts_nested_attributes_for :addresses, reject_if: { |attrs| ... } 

#OR 
accepts_nested_attributes_for :addresses, reject_if: :my_method 

def my_method 
    #some logic that returns true for invalid record 
end 
+0

感謝您的回覆,但這不是我想要實現的。我創建了一個類驗證器,我想在該類上使用我的* nested *關聯進行自定義驗證。經過太多嘗試後,我發現了導致*問題的原因*:**方括號語法**。我無法訪問我的關聯:'record [assocation]'。如果我使用點語法,它的工作原理**然而**我不能使用點語法,因爲它是一個通用的驗證器(動態)。 –

+2

@ dev_054但在這種情況下,您可以使用'record.send(assocation)',據我所知 – idej

+0

就是這樣。感謝它..你可以將它添加到你的答案,所以我可以檢查它。 –