Form fields autofilled on loading a signup page in Rails - html

I have this signup form code (the controller is added below) :
<%= form_with(model: #user, class: "shadow p-3 mb-3 bg-info rounded", local: true) do |f|%>
<div class="form-group row">
<%= f.label :username, class: "col-2 col-form-label text-light"%>
<div class="col-10">
<%= f.text_field :username, class: "form-control shadow rounded", placeholder: "Enter a username" %>
</div>
</div>
<div class="form-group row">
<%= f.label :email, class: "col-2 col-form-label text-light"%>
<div class="col-10">
<%= f.email_field :email, class: "form-control shadow rounded", placeholder: "Enter your e-mail address" %>
</div>
</div>
<div class="form-group row">
<%= f.label :password, class: "col-2 col-form-label text-light"%>
<div class="col-10">
<%= f.password_field :password, class: "form-control shadow rounded", placeholder: "Choose a password" %>
</div>
</div>
<div class="form-group row justify-content-center">
<%= f.submit class:"btn btn-outline-light btn-lg" %>
</div>
<% end %>
Even though I have placeholders set up (placeholder: "...."), when I load the page it becomes auto-filled with some personal values - e-mail + password.
The controller code for creating users is the following:
class UsersController <ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :require_user, only: [:edit, :update]
before_action :require_same_user, only: [:edit, :update, :destroy]
def show
#articles = #user.articles.paginate(page: params[:page], per_page: 2)
end
def index
#users = User.paginate(page: params[:page], per_page: 2)
end
def new
#user = User.new
end
def edit
end
def update
if #user.update(user_params)
flash[:notice] = "Your account information was successfully updated."
redirect_to #user
else
render 'edit'
end
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
flash[:notice] = "Welcome to the Alpha Blog #{#user.username}, you have successfully signed up."
redirect_to articles_path
else
render 'new'
end
end
def destroy
#user.destroy
session[:user_id] = nil if #user == current_user
flash[:notice] = "Account and all associaed articles successfully deleted."
redirect_to articles_path
end
private
def user_params
params.require(:user).permit(:username, :email, :password) #whitelisting
end
def set_user
#user = User.find(params[:id])
end
def require_same_user
if current_user != #user && !current_user.admin?
flash[:alert] = "You can only edit or delete your own profile"
redirect_to #user
end
end
end
Not sure how to disable that. Thanks!

form_with(model: #user, ... builds the form with whatever is in the #user variable.
Let's say you have a user like this:
$ #user = User.first
> #<User id: 1, email: "person#email.com", username: "Person", password_digest: [FILTERED]>
In this case, form_with fields will use the existing record values in the form.
If you've created a new user in the controller action for this view:
$ #user = User.new
> #<User id: nil, email: nil, username: nil, password_digest: nil>
then the form fields should be blank.
How to test if this is the issue:
Replace your #user with User.new:
<%= form_with(model: #user, ...
What else could be happening:*
The browser could be auto-filling form data, Chrome does this quite often.
A browser extension, like a password manager, could be auto-filling the form data

Related

What's wrong with my form in Ruby on Rails?

I'm trying to implement a prayer request and prayer response form, much like a micropost with a comment on it. The prayer requests are created and deleted as expected, but when I try to post a prayer response, it just reloads the page with no errors and no flash saying that the post was successful. This behavior happens wether the post is valid or not (no errors for a blank response, just a reload of the page) When I use the rails console, I'm able to build and save a prayer response successfully, and it shows up on rails server. What's wrong with my form? Based on the server log, I see that when I try to post a prayer response, it's using the RequestsController instead of the PrayerResponsesController. How do I fix this?
Here's my server log errors:
Started POST "/requests" for 127.0.0.1 at 2023-01-18 16:24:36 -0600
Processing by RequestsController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "content"=>"Prayer response...", "request_id"=>"150", "commit"=>"Respond in Prayer"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/helpers/sessions_helper.rb:18:in `current_user'
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/helpers/sessions_helper.rb:18:in `current_user'
Completed 400 Bad Request in 4ms (ActiveRecord: 0.1ms | Allocations: 2115)
ActionController::ParameterMissing (param is missing or the value is empty: request
Did you mean? request_id):
Here's my code:
controllers/prayer_responses_controller.rb
class PrayerResponsesController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
#prayer_response = current_user.prayer_responses.build(prayer_response_params)
if #prayer_response.save
flash[:success] = "Prayer Response created!"
redirect_back(fallback_location: root_url)
else
render 'static_pages/requests', status: :unprocessable_entity
end
end
def destroy
#prayer_response.destroy
flash[:success] = "Prayer Response deleted"
redirect_back_or_to( root_url, status: :see_other )
end
private
def prayer_response_params
params.require(:prayer_response).permit(:content, :request_id)
end
def correct_user
#prayer_response = current_user.prayer_responses.find_by(id: params[:id])
redirect_to root_url, status: :see_other if #prayer_response.nil?
end
end
views/static_pages/requests.html.erb
<% provide(:title, "Prayer Requests") %>
<div class="row">
<aside class="col-md-4">
<section class="request-form">
<%= render 'shared/request_form' %>
</section>
</aside>
<div class="col-md-8">
<h3>Prayer Requests</h3>
<% if Request.all != nil %>
<%= render Request.all %>
<% end %>
</div>
</div>
views/requests/_request.html.erb
<li id="request-<%= request.id %>" class="requests">
<%= link_to gravatar_for(request.user, size: 50), request.user %>
<span class="user"><%= link_to request.user.name, request.user %></span>
<span class="content"><%= request.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(request.created_at) %> ago.
<% if current_user?(request.user) %>
<%= link_to "delete", request, data: { "turbo-method": :delete,
"turbo-confirm": "Are you sure?"} %>
<% end %>
</span>
<% if current_user != nil %>
<span>
<%= render 'shared/prayer_response_form', request_id: request.id %>
</span>
<span>
<% if request.prayer_responses.any? %>
<ol class="prayer_responses">
<% request.prayer_responses.reverse.each do |prayer_response| %>
<%= render prayer_response %>
<% end %>
</ol>
<% end %>
</span>
<% end %>
</li>
views/prayer_responses/_prayer_response.html.erb
<li id="prayer_response-<%= prayer_response.id %>">
<%= link_to gravatar_for(prayer_response.user, size: 30), prayer_response.user %>
<span class="user"><%= link_to prayer_response.user.name, prayer_response.user %></span>
<span class="content"><%= prayer_response.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(prayer_response.created_at) %> ago.
<% if current_user?(prayer_response.user) %>
<%= link_to "delete response", prayer_response, data: { "turbo-method": :delete,
"turbo-confirm": "Are you sure?"} %>
<% end %>
</span>
</li>
views/shared/_prayer_response_form.html.erb
<%= form_with(model: #prayer_response) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<center>
<div class="field">
<%= f.text_area(:content, placeholder: "Respond to this prayer request...") %>
</div>
<div><%= f.hidden_field :request_id, value: request_id %></div>
<%= f.submit "Respond in Prayer", class: "btn btn-primary" %>
</center>
<% end %>
models/prayer_response.rb
class PrayerResponse < ApplicationRecord
belongs_to :user
belongs_to :request
default_scope -> { order( created_at: :desc) }
validates :user_id, presence: true
validates :request_id, presence: true
validates :content, presence: true, length: { maximum: 500 }
end
models/request.rb
class Request < ApplicationRecord
belongs_to :user
has_many :prayer_responses, dependent: :destroy
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :content, presence: true, length: { maximum: 280 }
end
db/migrate/20230113172701_create_prayer_responses.rb
class CreatePrayerResponses < ActiveRecord::Migration[7.0]
def change
create_table :prayer_responses do |t|
t.text :content
t.references :user, null: false, foreign_key: true
t.references :request, null: false, foreign_key: true
t.timestamps
end
add_index :prayer_responses, [:user_id, :request_id, :created_at]
end
end
db/migrate/20230107204925_create_requests.rb
class CreateRequests < ActiveRecord::Migration[7.0]
def change
create_table :requests do |t|
t.text :content
t.references :user, null: false, foreign_key: true
t.timestamps
end
add_index :requests, [:user_id, :created_at]
end
end
config/routes.rb
root "static_pages#home"
get "/help", to: "static_pages#help"
get "/about", to: "static_pages#about"
get "/contact", to: "static_pages#contact"
get "/new_public_prayers", to: "static_pages#new_public_prayers"
get "/signup", to: "users#new"
get "/login", to: "sessions#new"
post "/login", to: "sessions#create"
delete "/logout", to: "sessions#destroy"
resources :users do
member do
get :following, :followers
end
end
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :prayers, only: [:create, :destroy]
resources :requests, only: [:create, :destroy]
resources :prayer_responses, only: [:create, :destroy]
resources :comments, only: [:create, :destroy]
resources :private_prayers, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
get "/private_prayers", to: "static_pages#private_prayers"
get "/prayers", to: "static_pages#home"
get "/comments", to: "static_pages#home"
get "/requests", to: "static_pages#requests"
get "/prayer_responses", to: "static_pages#requests"
end
The answer, actually, was in the static_pages_controller.rb file... I needed to add #prayer_response = current_user.prayer_responses.build to the requests page's function...
class StaticPagesController < ApplicationController
def home
if logged_in?
#prayer = current_user.prayers.build
#comment = current_user.comments.build
#feed_items = current_user.feed.paginate(page: params[:page])
end
end
def help
end
def about
end
def contact
end
def new_public_prayers
end
def private_prayers
if logged_in?
#private_prayer = current_user.private_prayers.build
else
redirect_to root_url
end
end
def requests
if logged_in?
#request = current_user.requests.build
#prayer_response = current_user.prayer_responses.build
else
redirect_to root_url
end
end
end
This made sure that the proper controller was followed when building a new prayer response, etc.

Edit other user as admin, ruby on rails

I want, that a user with the admin role can edit other users from users/index.html.erb view. I'm not the first one asking this question, but all the given answers lack clear instructions.
So the problem is; after editing the fields, when I click on the 'Updtate' button in users/index.html.erb view, the page is reloaded but no changes appens.
Aditionnal infos: I'm using Devise and Omniauth facebook.
The users are display in the users/index via a partial:
<td>
<div class="field">
<%= f.text_field :name, class: 'form-control' %>
</div>
</td>
<td>
<div class="field">
<%= f.text_field :email, class: 'form-control' %>
</div>
</td>
<td>
<div class="actions">
<%= f.submit I18n.translate('control.update'), class: 'btn sign-up-button' %>
</div>
</td>
<td>
<!-- display a delete button if the user is not the current_user -->
<%= link_to(I18n.translate('control.delete'), user_path(user), :data => { :confirm => "Are you sure?" }, :method => :delete, :class => 'btn') unless user == current_user %>
</td>
users/index.html.erb:
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<h2 class="text-center"><%= I18n.translate('user.users_list') %></h2>
<div class="column">
<table class="table">
<tbody>
<% #users.each do |user| %>
<tr>
<%= render user %>
</tr>
<% end %>
</tbody>
</table>
</div>
<ul class=”pagination”>
<li><%= will_paginate(#users) %></li>
</ul>
</div>
</div>
</div>
My user_controller.rb
class UsersController < ApplicationController
before_action :ensure_admin, :except => :show
def index
#users = User.paginate(:page => params[:page], :per_page => 8)
end
def show
#user = User.find_by_name(params[:id])
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def destroy
user = User.find(params[:id])
user.destroy
redirect_to users_path, :notice => "User deleted."
end
private
def ensure_admin
if(current_user.role == 'admin')
return
end
redirect_to root_path, :alert => "Access denied."
end
def secure_params
params.require(:user).permit(:role)
end
def user_params
params.require(:user).permit(:email, :name, :password)
end
end
My routes:
Rails.application.routes.draw do
root to: 'pages#index'
get 'users/index'
# you can type '/users' to view the users
match '/users', to: 'users#index', via: 'get'
devise_for :users, :controllers => { :registrations => "registrations",
:path_prefix => 'd',
:omniauth_callbacks => "users/omniauth_callbacks" }
resources :users
scope '/:locale' do
devise_scope :user do
get 'login', to: 'devise/sessions#new'
end
devise_scope :user do
get 'signup', to: 'devise/registrations#new'
end
end
Here in the user_controller update action you are calling secure_params def, which is permitting only "role" field.
I think you should to use user_params in update action like below
def update
#user = User.find(params[:id])
if #user.update(user_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
Or you will have to permit other params also in secure_params def like
def secure_params
params.require(:user).permit(:role,:name,:email)
end
Hope it would help you.

Hash password not saved in the password column

I am trying to store hash password in my users table while registration. Please see my code:
users_controller.rb
def login
#title = 'Login'
#render layout: 'login'
end
def create_login
user = User.authenticate(params[:user][:username], params[:user][:password])
if user
log_in user
redirect_to '/admin'
else
flash[:danger] = 'Invalid email/password combination' # Not quite right!
redirect_to :back
end
end
def register
#user = User.new
#title = 'Register'
end
def create_register
params[:user][:uniq_id] = generate_uniq
#user = User.new(create_user_params)
#raise #user.inspect
respond_to do |format|
if #user.save
format.html { redirect_to :success, success: 'Registration was successfully created.' }
format.json { redirect_to :register, status: :created, location: #users }
else
format.html { render :register }
format.json { render json: #users.errors, status: :unprocessable_entity }
end
end
end
private
def create_user_params
params.require(:user).permit(:uniq_id, :name, :username, :email, :password, :password_confirmation, :password_salt, :dob, :address)
end
register.html.erb
<%= form_tag("/register", method: "post") do %>
<%#= form_tag(#user) do |f| %>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= text_field :user, :name, placeholder:'NAME', required: true %>
<div style="position: relative;">
<span id="chk-username" style="position: absolute;font-size: 12px;right: 2%; bottom: 5%; z-index: 9; display: block;"></span>
<%= text_field :user, :username, placeholder:'USERNAME', 'data-validate':"/users/check_username", required: true %>
</div>
<div style="position: relative;">
<span id="chk-email" style="position: absolute;font-size: 12px;right: 2%; bottom: 5%; z-index: 9; display: block;"></span>
<%= text_field :user, :email, placeholder:'EMAIL', 'data-validate':"/users/check_email", required: true %>
</div>
<%= password_field :user, :password, placeholder:'PASSWORD', required: true %>
<%= password_field :user, :password_confirmation, placeholder:'CONFIRM PASSWORD', required: true %>
<div class="submit">
<input type="submit" value="REGISTER" >
<input type="button" onclick="location.href = '<%= request.base_url %>/login'" value="LOGIN" >
</div>
<p>Forgot Password ?</p>
<% end %>
user.rb
class User < ActiveRecord::Base
#has_secure_password
attr_accessor :password
before_save :encrypt_password
validates :name, presence: true
validates :name, length: { minumum:2, maximum: 30 }
validates :password, :presence =>true,
:length => { :minimum => 6, :maximum => 40 },
:confirmation =>true
validates :username, :presence => true,
:uniqueness => { :case_sensitive => false }
email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
def self.authenticate(input_username, input_password)
user = find_by_username(input_username)
if user && user.password == BCrypt::Engine.hash_secret(input_password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
routes.rb
get 'register' => 'users#register'
post 'register' => 'users#create_register'
Here is my database table.
users.sql (customize table)
+----+----------+------------+-----------+----------------+
| id | name | username | password | password_salt |
+----+----------+------------+-----------+----------------+
| 1 | chinmay | chinu | NULL |$2a$10$15fWDt.. |
| 2 | sanjib | sanjib | NULL |$2a$10$85DyMr.. |
+----+----------+------------+-----------+----------------+
I get NULL value in my password column. Please help me and let me know where the error is in my code.
Your main error is that your are using attr_accessor :password to create a getter/setter for the password attribute that overrides the getter and setter that ActiveRecord creates from the database schema.
However your whole approach to password encryption is flawed - you should have password as a purely virtual attribute and name your database column password_digest or encrypted_password.
Unless its for pure learning purposes should use the has_secure_password macro that Rails provides instead of reinventing the password encryption wheel and getting hacked.
1. Add a password_digest column to user:
rails g migration AddPassWordDigestToUser password_digest:string:index
You might want to remove the password_salt column as well as it is not used by ActiveModel::SecurePassword.
class AddPassWordDigestToUser < ActiveRecord::Migration
def change
add_column :users, :password_digest, :string
add_index :users, :password_digest
remove_column :users, :password_salt
remove_column :users, :password
end
end
2. Add has_secure_password to the User model:
class User < ActiveRecord::Base
has_secure_password
end
3. RESTful routes
You may want to correct your routes so they are resource oriented and not action oriented and follow the rails conventions:
GET /registrations/new registations#new - sign up form
POST /registrations registations#create - create user
GET /sessions/new sessions#new - sign in form
POST /sessions sessions#create - sign in user
You can setup the routes with just:
resources :registrations, only: [:new, :create]
resources :sessions, only: [:new, :create]
See Rails Routing from the Outside In.
4. Binding forms and controllers.
You are setting up the controller properly however your form is not bound to the #user model instance you are creating in your controller.
This means that the values the user enters disappear after a unsuccessful form submission.
Also pay attention to the pluralization and naming of your variables! You are inconsistently using #user and #users. In this case #users will always be nil and cause an error.
app/controllers/registrations_controller.rb:
class RegistationsController < ApplicationController
def new
#user = User.new
end
def create
# Use a block instead of messing with the incoming params.
#user = User.new(user_params) do |u|
u.uniq_id = generate_uniq
end
if #user.save
respond_to do |format|
format.html { redirect_to root_path, success: "Welcome #{#user.email}" }
format.json { status: :created, location: #user }
end
else
respond_to do |format|
format.html { redirect_to :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
app/views/registrations/new.html.erb:
<%= form_for(#user, url: registrations_path) do |f| %>
<div class="row">
<%= f.label :email %>
<%= f.text_field :email %>
</div>
<div class="row">
<%= f.label :password %>
<%= f.password_field :password %>
</div>
<div class="row">
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
</div>
<% end %>

Getting undefined method 'parent'

So i asked this question a while back before but i still cant seem to get this right . im trying to make my comment model make comments for both topics and posts. i just want Comments controller to be able to handle comments going to post or topic.
routes :
resources :topics, :posts do
resources :comments, only: [:create, :destroy]
end
Topic Model:
has_many :comments, dependent: :destroy
Comment Model:
belongs_to :post
belongs_to :topic
Post:
has_many :comments, dependent: :destroy
Comments Controller :
def create
if params[:post_id]
#parent = Post.find(params[:post_id])
#comment = #parent.comments.new(comment_params)
#comment.user = current_user
if #comment.save
flash[:notice] = "Comment saved successfully."
redirect_to [#parent.topic, #parent]
else
flash[:alert] = "Comment failed to save."
redirect_to [#parent.topic, #parent]
end
elsif params[:topic_id]
#parent = Topic.find(params[:topic_id])
#comment = #parent.comments.new(comment_params)
#comment.user = current_user
if #comment.save
flash[:notice] = "Comment saved successfully."
else
flash[:alert] = "Comment failed to save."
end
end
end
def comment_params
params.require(:comment).permit(:body)
end
comment/form.html
<%= form_for [#parent, #comment] do |f| %>
<div class="form-group">
<%= f.label :body, class: 'sr-only' %>
<%= f.text_field :body, class: 'form-control', placeholder: "Enter a new comment" %>
</div>
<%= f.submit "Submit Comment", class: 'btn btn-default pull-right' %>
<% end %>
I keep getting undefined local variable or method parent when trying to go to my topic/show view
also how can i implement comments to show up on topic/post view
undefined local variable or method parent
You need to change your local variables (parent & comment) to instance variables (#parent & #comment) in the controller action and as well in the view in order to use those in the view.
The below should work
<%= form_for [#parent, #comment] do |f| %>
<div class="form-group">
<%= f.label :body, class: 'sr-only' %>
<%= f.text_field :body, class: 'form-control', placeholder: "Enter a new comment" %>
</div>
<%= f.submit "Submit Comment", class: 'btn btn-default pull-right' %>
<% end %>
Also I've noticed that there are two #parent & #parant variables defined in the controller action. If its a typo then correct it.

First argument in form cannot contain nil or be empty

Ive looked at atleast 8 other forums with the same title and none of the ones read helped me at all!
So im using a partial to render a form to a edit.html.erb page and a new.html.erb page. My controller page works except for the edit page!
Here is my code for my controller page :
class ProfilesController < ApplicationController
def new
# form where a user can fill out their own profile.
#user = User.find( params[:user_id] )
#profile = Profile.new
end
def create
#user = User.find( params[:user_id] )
#profile = #user.build_profile(profile_params)
if #profile.save
flash[:success] = "Profile Updated!"
redirect_to user_path( params[:user_id] )
else
render action: :new
end
end
def edit
#user = User.find( params[:id] )
#profile = #user.profile
end
private
def profile_params
params.require(:profile).permit(:first_name, :last_name, :job_title, :phone_number, :contact_email, :description)
end
end
my edit.html.erb page:
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">Edit Your Profile</h1>
<p class="text-center">Be a part of the Dev Match community and fill out your profile!</p>
<div class="well">
<%= render 'form' %>
</div>
</div>
</div>
my new.html.erb page:
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">Create Your Profile</h1>
<p class="text-center">Be a part of the Dev Match community and fill out your profile!</p>
<div class="well">
<%= render 'form' %>
</div>
</div>
</div>
and _form.html.erb:
<%=form_for (#profile) , url: user_profile_path do |f| %>
<div class="form-group">
<%= f.label :first_name %>
<%= f.text_field :first_name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :last_name %>
<%= f.text_field :last_name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :job_title %>
<%= f.select :job_title, ['Developer', 'Entrepreneur', 'Investor'], {}, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :phone_number %>
<%= f.text_field :phone_number, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :contact_email %>
<%= f.text_field :contact_email, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.submit "Update Profile", class: 'btn btn-primary' %>
</div>
<% end %>
You change your code into this:
def edit
#user = User.find(params[:user_id])
#profile = #user.profile
end
#user is null because the id does not exist in DB.
If you create a new instance of User in the action new you can use the same object in the action create without use the method User.find
As improvement, try to add before_action in your controller.
class ProfilesController < ApplicationController
before_action :prepare_model, except: [:new, :create]
def new
# form where a user can fill out their own profile.
#user = User.new
#profile = Profile.new
end
def create
#profile = #user.build_profile(profile_params)
if #profile.save
flash[:success] = "Profile Updated!"
redirect_to user_path( params[:user_id] )
else
render action: :new
end
end
def edit
#profile = #user.profile
end
private
def prepare_model
#user = User.find(params[:user_id])
raise ActiveRecord::RecordNotFound if #user.nil?
end
def profile_params
params.require(:profile).permit(:first_name, :last_name, :job_title, :phone_number, :contact_email, :description)
end
end