I have a User model (using Devise) and a Listing model. User has_many :listings and Listing belongs_to :user.
The user has email, password and phone number attributes, but when creating an account, only email and password are required. Phone number can be left blank.
When a logged-in user creates a Listing, I'd like to provide the option for the current user to include his phone number using the same form. The expectation is to store the phone number of the user who is creating the listing.
I've created forms to accept nested attributes for child objects before, but not for parent object like this case. I haven't figured out how to get the form to do this, and whether I need to change something in the controller or models. Any help is appreaciated.
User model
class User < ApplicationRecord
has_many :listings, dependent: :destroy
end
Listing model
class Listing < ApplicationRecord
belongs_to :user
end
Listings controller
def create
@listing = current_user.listings.build(listing_params)
respond_to do |format|
if @listing.save
format.html { redirect_to listing_url(@listing), notice: "Listing was successfully created." }
format.json { render :show, status: :created, location: @listing }
else
...
end
end
end
New Listing Form
<%= form_with model: @listing do |f| %>
<div class="field">
<%= f.label :title, class: "label required" %>
<div class="control">
<%= f.text_field :title, autofocus: true, autocomplete: "title", required: true, class: "input" %>
</div>
</div>
...
<% end>
Thanks