JShoe
JShoe

Reputation: 3428

Rails assign two attributes with one form item

I have an object with attributes first_team_name and second_team_name, and a list that has pairs of [team1, team2] values.

I would like to be able to have it so when I select an object in the form, it assigns team1 to first_team_name and team2 to second_team_name, but I have no idea how to split those values accordingly.

Is there anyway to split the values of my collection and put them to two different attributes of my object?

Upvotes: 0

Views: 47

Answers (2)

pierallard
pierallard

Reputation: 3371

You can define 2 functions in your model

def team_names
  return "#{first_team_name},#{second_team_name}"
end

def team_names=(values)
  self.first_team_name, self.last_team_name = values.split(',')
end

Warnings

  • your select values must be like 'toto,titi'.
  • Choose an other separator if team name can include commas.

Upvotes: 2

supernova32
supernova32

Reputation: 321

I think it is possible by parsing the arguments in the controller and then assigning them to whichever object you want. I don't know if this is best practice, though. You will need to modify the update method of the Controller.

Upvotes: 0

Related Questions