Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combined fields in Rails

What is the best way to solve the problem? User inputs and edits string "tom had a dog". I'd like the model and database to store "tom" and "had a dog" as separate fields. I recall solving this problem when dealing with telephone number strings but can't quite recall how I did.


1 Answers

You could create a setter in your model that isn't mapped to a database field... this setter would contain the logic that determines how the string is split in two, then sets the two fields accordingly:

class MyModel

  def mysetter=(string)
      # your logic to split up the string
      field1 = ...
      field2 = ...
  end
end
like image 72
dstnbrkr Avatar answered Dec 31 '25 19:12

dstnbrkr