I have a user model and a town model. A user belongs_to a town:
# models/user.rb
class User < ApplicationRecord
belongs_to :town
accepts_nested_attributes_for :town
validates :last_name, presence: true
end
# models/town.rb
class Town < ApplicationRecord
has_many :users
validates :name, presence: true
validates :name, uniqueness: true
end
You go to create a new user record: there is a text_box in order to put in the associated town's name. When submitted, the rails application should do the following:
- use
find_or_create_by. go and check if there already exists atownrecord with thenameattribute passed in.- If a
townrecord DOES exist with that givennameattribute, just associate that existingtownrecord to this newuserrecord - If a
townrecord DOES NOT exist with that givennameattribute, then create a newtownrecord with thatnameattribute, and associate that one to thisuserrecord
- If a
- If any validations fail, do not create a
userrecord or atownrecord and re-render the form.
I am having real trouble with this. This question suggests putting autosave on the belongs_to :town statement, as well as defining a method called autosave_associated_records_for_town. However: I just could not get that to work.
Appreciate it!

