ruby on rails - Automatic naming of objects based on associations with other models -
i have 3 models "input", "mechanism", , "output".
mechanism 'has_one' :input , 'has_one' :output.
i want make mechanism object has name attribute "the effect of input x on output y".
here tried:
class mechanism include neo4j::activenode property :name, default: 'newmechanism#{self.class.count}' has_one :in, :input, class_name: 'input' has_one :out, :output, class_name: 'output' after_create :name_mechanism def name_mechanism self.update_attributes(name: "effect of #{self.input.name} on #{self.output.name}") end end but when initialize object in console, error
nomethoderror: undefined method `name' nil:nilclass app/models/mechanism.rb:12:in 'name_mechanism'
so yeah using neo4j database, suspect isn't neo4j issue, rather weak understanding of callbacks in rails. advice?
your code assuming every mechanism have associated input , output. need cater situations not. this
class mechanism include neo4j::activenode property :name, default: 'newmechanism#{self.class.count}' has_one :in, :input, class_name: 'input' has_one :out, :output, class_name: 'output' before_create :name_mechanism def name_mechanism if self.name.blank? self.name = self.default_name end end def default_name "effect of #{self.input ? self.input.name : "<input not set>"} on #{self.output ? self.output.name : "<output not set>"}" end end note i've changed callback before_create since better place set default name. note name_mechanism keeps name if it's got non-blank one.
Comments
Post a Comment