0

For some reason rubocop is choking on this code I have in my model to properly address accepts_nested_attributes_for to work like find or create. When I tried to remove the self calls it blows up. At this point I am deferring to experts before I shut that darn cop off. Thoughts?

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

4

2 回答 2

0

This would make Rubocop happy:

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

P.S. I do not see the logic behind this method - you are checking, if company association is present, and if it is you are assigning association again with this same company.

Method does not make sense - I think you'd be better of deleting it altogether.

If you want to make sure, that company is always present, just check add presence validation:

validates :company, presence: true
于 2016-02-17T07:07:56.840 回答
0

In order to fix the issue with find or create by and pass through rubocop successfully this variation solved the problem

  private

  def find_company
    existing_company = Company.where(email: company.email) if company
    self.company = existing_company.first if existing_company.count > 0
  end
于 2016-02-18T23:14:20.837 回答