0

Im using virtual attributes to concat and form a address before i save the user. So when they click edit user i would like to populate the fields in the form again. Every time i try to assign them they come back nil?

This is what i call from devise registrations controller before_action edit:

def test
 resource.populate_address_attributes
end

and here is the method im trying to work with:

def populate_address_attributes
  if address == nil || address == ""
    return false
  else
    attributes = address.split(",")
    [self.number, self.street_name, self.area, self.postcode, self.state].each { |x| x = attributes.delete_at[0]}
  end
end

all i'm getting is this:

=> [nil, nil, nil, nil, nil]

maybe i'm trying to make it to complicated?

6
  • Ill add the attributes array is populated correctly with the address split up Commented Oct 22, 2018 at 11:02
  • Why do you store the address as a single comma separated string? Commented Oct 22, 2018 at 11:28
  • because geocoder allows it with comma's and i cant split with " " incase of multiple words in the street name or city Commented Oct 22, 2018 at 11:41
  • Storing the address as a single concatenated comma seperated string seems like a really bad idea since addresses may actually contains commas (596 Ocean Blvd, APT 162) for example. The idea of being able to parse addresses with simple methods is utterly flawed. You're basically taking good seperated data and turing it into junk. Commented Oct 22, 2018 at 17:01
  • @max ok seems fair, how would you suggest i go about it? Commented Oct 23, 2018 at 2:18

1 Answer 1

1

When you are passing [self.number, self.street_name] etc you are passing the value of those attributes (which are nil and hence immutable).

Try this

def populate_address_attributes
  if address == nil || address == ""
    return false
  else
    attributes = address.split(",")
    [:number, :street_name, :area, :postcode, :state].each_with_index do |field, index|
      self.public_send("#{field}=", attributes[index])
    end
  end
end
Sign up to request clarification or add additional context in comments.

11 Comments

can't write unknown attribute field
sorry, there was a bug, fixed. Try again
Should had been self[field] instead of self[:field]
now its throwing "*** ActiveModel::MissingAttributeError Exception: can't write unknown attribute number" In byebug i can set self.number to 3 and then self[field] is showing nil and it should be 3. Im a bit confused!
So i think i understand it, basically i was storing the values of the variables in the array, not setter methods. so by calling public send(number, 4) on the user object its effectively calling the setter method in this case?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.