2016-02-17 37 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 
相关问题