2016-02-17 36 views
0

由於某種原因,rubocop窒息了我在我的模型中的代碼,以正確地解決accepts_nested_attributes_for像查找或創建一樣工作。當我試圖刪除self的呼叫時,它爆炸了。在此之前,我將專家關閉之前,我正在推遲專家。思考?rubocop風格模型自我需要,但觸發警告

class Job < ActiveRecord::Base 
    belongs_to :company 
    before_validation :find_company 

    accepts_nested_attributes_for :company 

    private 

    def find_company 
    if self.company 
     self.company = Company.where(email: self.company.email).first_or_initialize 
    end 
    end 
end 

enter image description here

回答

0

這將使Rubocop高興:

def find_company 
    self.company = Company.where(email: company.email).first_or_initialize if company 
end 

附:我沒有看到這種方法背後的邏輯 - 您正在檢查,如果公司關聯存在,並且如果它是,則您正在與同一家公司再次分配關聯。

方法沒有意義 - 我想你會更好地完全刪除它。

如果你想確保,該公司是始終存在的,只是檢查添加存在驗證:

validates :company, presence: true 
+0

當您使用您必須考慮尋找或創造嵌套屬性由http://stackoverflow.com/questions/3579924/accepts-nested-attributes-for-with-find-or-create = >我在這裏錯過了什麼?這確實修復了rubocop。 –

+0

@chrishough無論如何,至於rubocop - 只有在分配它時才使用'self.attribute',比如'self.age = 25;保存!',其他任何時候它都可以在沒有'self'的情況下工作 –

+0

@chrishough也關於您提供的參考 - 我沒有時間仔細閱讀,但我敢打賭,刪除'before_validation'並添加出席驗證會工作 –

0

爲了解決該問題與find或通過創建並通過rubocop成功這種變化解決了問題

private 

    def find_company 
    existing_company = Company.where(email: company.email) if company 
    self.company = existing_company.first if existing_company.count > 0 
    end 
相關問題