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 atown
record with thename
attribute passed in.- If a
town
record DOES exist with that givenname
attribute, just associate that existingtown
record to this newuser
record - If a
town
record DOES NOT exist with that givenname
attribute, then create a newtown
record with thatname
attribute, and associate that one to thisuser
record
- If a
- If any validations fail, do not create a
user
record or atown
record 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!