I'm struggling to figure out exactly how to get this to work, but essentially I have 2 models:
class User
class Profile
One User has One Profile.
I also have a SettingsController with "profile" and "update" actions:
class SettingsController < ApplicationController
def profile
@profile = User.find_by_id(current_user).profile
end
def update
set_profile
respond_to do |format|
if @profile.update(profile_params)
format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }
else
format.html { render :edit }
end
end
end
private
def profile_params
params.require(:profile).permit(:name)
end
end
And the /settings/profile page:
<h1>Settings</h1>
<div>
<div>
Name: <%= @profile.name %>
</div>
<%= form_with(model: @profile, local: true) do |form| %>
<div class="field">
<%= form.label :username %>
<%= form.text_field :username %>
</div>
<div class="field">
<%= form.label :surname %>
<%= form.text_field :surname %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
</div>
My routes:
get 'settings/profile', to: 'settings#profile', as: :settings_profile
post 'settings/profile', to: 'settings#update', as: :update_settings_profile
How can I get my form (from SettingsController) to allow fields for my User and Profile models?
*Edit
I have overridden my profile_path to pull from the username:
def profile_path(profile)
'/' + 'profiles' + '/' + profile.user.username
end
Currently, when I load the page containing the form, I get this error:
wrong number of arguments (given 2, expected 1)
When you define the form as
<%= form_with(model: @profile, local: true) do |form| %>
, it is equivalent to<form action="/profiles/1" method="post" data-remote="false">
. You need to tell Rails to map the form to the custom url like soAnd you need to whitelist
username
andsurname
in theprofile_params
in order to reflect the changes in the DB.