patternrubyrailsMinor
Rails refactoring has_many
Viewed 0 times
refactoringrailshas_many
Problem
I have a RoR 4 app, and its model have these associations:
So, you see that these associations similar, but
has_many :accreditations
has_one :legal, -> { where(kind_cd: Accreditation.legal) }, class_name: 'Accreditation'
has_many :departments, -> { where(kind_cd: Accreditation.department) }, class_name: 'Accreditation'So, you see that these associations similar, but
legal & departments have more conditions than accreditations. Can I replace class_name: 'Accreditation' with something like using :accreditations?Solution
There are two ways to tackle this situation. One of them is what you did: follow the Law of Demeter; I don't have any advice to improve your code. The second way is move the logic to the other model. In that case you'd write:
Both are ok even though I prefer the second because the logic of departments/legal is within the accreditation model.
class Company
has_many :accreditations
end
class Accreditation
scope :departments, where(kind_cd: department)
def self.legal
where(kind_cd: legal).first
end
endBoth are ok even though I prefer the second because the logic of departments/legal is within the accreditation model.
Code Snippets
class Company
has_many :accreditations
end
class Accreditation
scope :departments, where(kind_cd: department)
def self.legal
where(kind_cd: legal).first
end
endContext
StackExchange Code Review Q#45405, answer score: 4
Revisions (0)
No revisions yet.