Kirk
Kirk

Reputation: 19

Access an attribute from other model

This is a part of my model (Partner)

before_validation(on: :create) do
    self.name = name.upcase
    self.institution = institution.upcase
    self.position = position.upcase
    self.street = street.upcase
    self.neighborhood = neighborhood.upcase
    self.city = city.upcase
    self.state = state.upcase
    self.email = email.upcase
    self.birth_city = birth_city.upcase
    self.spouse = spouse.upcase
  end

street and neighborhood are attributes from address model. By this way, i´m getting an error before saving it to db. How can I solve it?

Upvotes: 0

Views: 144

Answers (1)

user419017
user419017

Reputation:

What you might be better doing is delegating those attributes to the Address model, and using autosave to have them persist when you save the Partner model..

class Partner
  has_one :address, autosave: true

  delegate :street, :neighborhood, to: :address

  # callback code here
end

If you want to upcase all attributes, you can use a combination of assign_attributes and transform_values:

before_validation(on: :create) do
  assign_attributes(attributes.transform_values(&:upcase))
end

Upvotes: 1

Related Questions