ActiveModel ForbiddenAttributesError - ruby-on-rails

Help me please. Rails swear...
What should I change? I allowed all parameters (permit_params), but this does not help:
ActiveModel::ForbiddenAttributesError
Extracted source (around line #17):
#user = User.where(id: params[:id]).first_or_create
#user.superadmin = params[:user][:superadmin]
#user.attributes = params[:user].delete_if do |k, v|
(k == "superadmin") ||
(["password", "password_confirmation"].include?(k) && v.empty? && !#user.new_record?)
end
"config.action_controller.permit_all_parameters = true" solves the problem. But I do not want to disable strong_parameters.
UPDATE
app/admin/user.rb
ActiveAdmin.register User do
form do |f|
f.inputs "User Details" do
f.input :email
f.input :password
f.input :password_confirmation
f.input :superadmin, :label => "Super Administrator"
end
f.actions
end
create_or_edit = Proc.new {
#user = User.where(id: params[:id]).first_or_create
#user.superadmin = params[:user][:superadmin]
#user.attributes = params[:user].delete_if do |k, v|
(k == "superadmin") ||
(["password", "password_confirmation"].include?(k) && v.empty? && !#user.new_record?)
end
if #user.save
redirect_to :action => :show, :id => #user.id
else
render active_admin_template((#user.new_record? ? 'new' : 'edit') + '.html.erb')
end
}
member_action :create, :method => :post, &create_or_edit
member_action :update, :method => :put, &create_or_edit
permit_params :authenticity_token, :commit, :id, user: [:email, :password, :password_confirmation, :superadmin]
end
P.S. I worked on this guide.
The problem is very similar to this problem: I get ActiveModel::ForbiddenAttributesError with Active Admin and Devise I get this error when I create a new user in the administration panel ActiveAdmin.
UPDATE1
console
Started POST "/admin/users" for 127.0.0.1 at 2017-12-08 22:57:04 +0300
Processing by Admin::UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"***********", "user"=>{"email"=>"test#test.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "superadmin"=>"0"}, "commit"=>"Create User"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL ORDER BY "users"."id" ASC LIMIT $1 [["LIMIT", 1]]
(3.0ms) BEGIN
(0.4ms) ROLLBACK
Completed 500 Internal Server Error in 24ms (ActiveRecord: 5.2ms)
ActiveModel::ForbiddenAttributesError
ActiveModel::ForbiddenAttributesError):
app/admin/user.rb:17:in `block (2 levels) in <top (required)>'

I have to agree with the answer given to the question you referenced, per the doc please try:
permit_params :email, :password, :password_confirmation, :superadmin

Related

Retrieving data from nested form

I am trying to re-create a stack overflow like app. One user asks a question, and others can answer. I have a nested form indented on the question's page to get answers from other users.
I am having a difficult time to retrieve the data after the answer is posted, and I have set #answer incorrectly on the questions controller page in the update action, and I can't figure out how to properly retrieve this variable given that the params coming through the questions_controller does not have details of the answer set separately. How do I retrieve the params part related to #answer so that I can set the variable, or maybe I need to use different routes for that?
My form looks like this:
<%= form_for #question do |form| %>
<%=form.fields_for :answer do |answer_form| %>
<div class="form-group">
<%=answer_form.text_area :answer_attributes, placeholder: "Add your answer", rows:10, class:"form-control" %>
<%=answer_form.hidden_field :user_id, value: current_user.id, class:'d-none' %>
<%=answer_form.hidden_field :question_id, value: #question.id %>
</div>
<% end %>
<div>
<%=form.submit 'Post Your Answer', class: 'btn-primary' %>
</div>
<% end %>
My Question model looks like this:
class Question < ApplicationRecord
has_many :answers, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :answers
validates :headline, presence: true , length: { minimum: 20 }
validates :body, presence: true, length: { minimum: 50 }
validates_associated :answers
end
and the Answer model is:
class Answer < ApplicationRecord
belongs_to :user
belongs_to :question
validates :body, presence: true, length: { minimum: 50 }
end
Questions controller:
class QuestionsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_question, except: [:index, :new, :create]
def index
#questions = Question.all.order("id DESC")
end
def show
#question = Question.find(params[:id])
#user = User.find(#question.user_id)
#answers = #question.answers
#answer = Answer.new
end
def new
#question = Question.new
#question.answers.new
end
def create
#question = current_user.questions.new(question_params)
if #question.save
flash[:notice] = "You have successfully posted your question"
redirect_to #question
else
#errors = #question.errors.full_messages
render action: :new
end
end
def edit
set_question
#question = Question.find(params[:id])
end
def update
#question = Question.find(params[:id])
#question.update(question_params)
#answer = #question.answers.new(question_params)
#question.answers.first.user_id = current_user.id
if #question.save
flash[:notice] = "You have sucessfully posted your answer"
redirect_to #question
else
redirect_to new_question_answer_path(#answer), flash: { danger: #question.errors.full_messages.join(",")}
end
end
private
def set_question
#question = Question.find(params[:id])
end
def question_params
params.require(:question).permit(:headline, :body, :user_id, :answer, answers_attributes:[:body, :user_id, :question_id])
end
end
Answers controller:
class AnswersController < ApplicationController
before_action :find_question
def index
#answers = #question.answers
#user = User.find(#question.user_id)
end
def show
#answer = Answer.find(params[:id])
#user = User.find(#question.user_id)
end
def new
#answer = Answer.new(:question_id => #question.id)
end
def create
#answer = Answer.new(answer_params)
if #answer.save
flash[:notice] = "You have sucessfully created the answer."
redirect_to(answers_path(#answer, :question_id => #question.id))
else
flash[:alert] = "Failed to save the answer."
#errors = #answer.errors.full_messages
render :new
end
end
def edit
#answer = Answer.find(params[:id])
end
def update
#answer = Answer.find(params[:id])
if #answer.update_attributes(answer_params)
flash[:notice] = "You have sucessfully updated the answer."
redirect_to(answer_path(#answer, :question_id => #question.id))
else
render :edit
end
end
def delete
#answer = Asnwer.find(params[:id])
end
def destroy
#answer = Answer.find(params[:id])
#answer.destroy
flash[:notice] = "Answer was destroyed"
redirect_to(answers_path)
end
private
def answer_params
params.require(:answer).permit(:body, :user_id, :question_id)
end
def find_question
#question = Question.find(params[:question_id])
end
end
My routes file looks like this:
Rails.application.routes.draw do
get 'questions/index'
root to: 'questions#index'
resources :questions do
resources :answers
end
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
UPDATE: here are the logs from the moment the server was started and the index page displayed to the moment where I go to the questions page and log the answer
rails server
=> Booting Puma
=> Rails 5.2.2 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.0 (ruby 2.6.0-p0), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
Started GET "/questions/11/answers" for 127.0.0.1 at 2019-03-07 16:10:13 +0600
(1.4ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
↳ /Users/irina/.rvm/gems/ruby-2.6.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
Processing by AnswersController#index as HTML
Parameters: {"question_id"=>"11"}
Question Load (0.8ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
↳ app/controllers/answers_controller.rb:65
User Load (2.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/answers_controller.rb:6
Rendering answers/index.html.erb within layouts/application
Answer Load (0.9ms) SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = $1 [["question_id", 11]]
↳ app/views/answers/index.html.erb:11
User Load (1.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/views/answers/_new.html.erb:7
Rendered answers/_new.html.erb (61.7ms)
Rendered answers/index.html.erb within layouts/application (92.7ms)
[Webpacker] Compiling…
Started GET "/questions/11/answers" for 127.0.0.1 at 2019-03-07 16:10:18 +0600
Processing by AnswersController#index as HTML
Parameters: {"question_id"=>"11"}
Question Load (1.4ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
↳ app/controllers/answers_controller.rb:65
User Load (1.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/answers_controller.rb:6
Rendering answers/index.html.erb within layouts/application
Answer Load (1.3ms) SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = $1 [["question_id", 11]]
↳ app/views/answers/index.html.erb:11
User Load (1.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/views/answers/_new.html.erb:7
Rendered answers/_new.html.erb (9.3ms)
Rendered answers/index.html.erb within layouts/application (18.5ms)
Completed 200 OK in 133ms (Views: 108.3ms | ActiveRecord: 18.4ms)
[Webpacker] Compilation failed:
Hash: 53a953077891e4cef2e8
Version: webpack 3.12.0
Time: 2928ms
Asset Size Chunks Chunk Names
application-c57a289721a93641de38.js 3.1 kB 0 [emitted] application
application-c57a289721a93641de38.js.map 2.49 kB 0 [emitted] application
manifest.json 142 bytes [emitted]
[0] ./app/javascript/packs/application.js 346 bytes {0} [built] [failed] [1 error]
ERROR in ./app/javascript/packs/application.js
Module build failed: SyntaxError: Unexpected token (14:15)
12 | if(window.railsEnv && window.railsEnv === 'development'){
13 | try {
> 14 | render(<App />, reactElement)
| ^
15 | } catch (e) {
16 | render(<RedBox error={e} />, reactElement)
17 | }
Completed 200 OK in 11715ms (Views: 11626.9ms | ActiveRecord: 27.7ms)
Started PATCH "/questions/11" for 127.0.0.1 at 2019-03-07 16:10:41 +0600
Processing by QuestionsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"q7HQt4uGPwBIIz0icswfJLWMRk6MiopIfWu9JBcjkuX1VpGBdwlwZu903NDuebSaX8Y90VHnvcEoaV8unV2zkw==", "question"=>{"answer"=>{"answer_attributes"=>"This is the test answer to see how the information goes through", "user_id"=>"3", "question_id"=>"11"}}, "commit"=>"Post Your Answer", "id"=>"11"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ /Users/irina/.rvm/gems/ruby-2.6.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
Question Load (0.5ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
↳ app/controllers/questions_controller.rb:55
CACHE Question Load (0.0ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
↳ app/controllers/questions_controller.rb:39
Unpermitted parameter: :answer
(0.5ms) BEGIN
↳ app/controllers/questions_controller.rb:40
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/questions_controller.rb:40
Answer Load (0.5ms) SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = $1 [["question_id", 11]]
↳ app/controllers/questions_controller.rb:40
(0.3ms) COMMIT
↳ app/controllers/questions_controller.rb:40
Unpermitted parameter: :answer
(0.3ms) BEGIN
↳ app/controllers/questions_controller.rb:44
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/questions_controller.rb:44
(0.4ms) ROLLBACK
↳ app/controllers/questions_controller.rb:44
Completed 500 Internal Server Error in 97ms (ActiveRecord: 8.3ms)
ActionController::UrlGenerationError (No route matches {:action=>"new", :controller=>"answers", :question_id=>nil}, missing required keys: [:question_id]):
app/controllers/questions_controller.rb:48:in `update'
UPDATE NO 2. It looks like because of this falsely set #answer the #question does not get saved as intended and the second part of the conditional kicks redirecting to the new_question_answer_path. I tried to update it to edit_question_answer_path and it gives the same error that no route matches.
If I open the answer in Pry I get the following object:
[1] pry(#<QuestionsController>)> #answer
=> #<Answer:0x00007fc3ec823c98
id: nil,
body: nil,
question_id: 11,
user_id: 3,
selected: nil,
created_at: nil,
updated_at: nil>
UPDATE No 3
Looks like changing my routes.rb to
Rails.application.routes.draw do
resources :questions, :has_many => :answers
root to: 'questions#index'
resources :questions do
resources :answers
end
devise_for :users
end
and also changing the form for the answer to this
<h2> Your Answer </h2>
<%= form_for [#question, Answer.new] do |form| %>
<div class="form-group">
<%=form.text_area :body, placeholder: "Add your answer", rows:10, class:"form-control" %><br>
<%=form.hidden_field :user_id, value: current_user.id, class:'d-none' %>
<%=form.hidden_field :question_id, value: #question.id %>
</div>
<div>
<%=form.submit 'Post Your Answer', class: 'btn-primary' %>
</div>
<% end %>
did the trick and helped to fix the problem. I am not sure if this is a perfect fix though)
Looks like changing my routes.rb to
Rails.application.routes.draw do
resources :questions, :has_many => :answers
root to: 'questions#index'
resources :questions do
resources :answers
end
devise_for :users
end
and also changing the form for the answer to this
<%= form_for [#question, Answer.new] do |form| %>
<div class="form-group">
<%=form.text_area :body, placeholder: "Add your answer", rows:10,
class:"form-control" %><br>
<%=form.hidden_field :user_id, value: current_user.id, class:'d-none' %>
<%=form.hidden_field :question_id, value: #question.id %>
</div>
<div>
<%=form.submit 'Post Your Answer', class: 'btn-primary' %>
</div>
<% end %>
did the trick and helped to fix the problem. I am not sure if this is a perfect fix though)

Unpermitted parameter with has_many_and_belongs_to :param, through :param

I am having trouble inputting data into my new model.
I created a new model so I can assign Users to Affiliates.
I have a Users, Affiliates, and UserAffiliates model.
UserAffiliates:
belongs_to :users
belongs_to :affiliates
User:
has_and_belongs_to_many :user_affiliate
has_and_belongs_to_many :affiliate, through: :user_affiliate, optional: true
Affiliate:
has_many :user_affiliates
has_many :users, through: :user_affiliates
How it works, is an affiliate can have many users, but a user will ever only have one affiliate. I then have a commission column within the UserAffiliates table to set the commission based on a user by user basis.
I created this form, and it doesn't seem to be working (which is stemmed from a <% #users.each do |user| %> that goes through each user in a table:
<%= form_for user, remote: true do |f| %>
<% f.fields_for :user_affiliates, remote: true do |f| %>
<%= f.text_field :affiliate_id, class: "form-control" %>
<%= f.submit "Add Affiliate", data: {confirm: "Are you sure?"}, class: "btn btn-light" %>
<% end %>
<% end %>
I get this error:
Parameters: {"utf8"=>"✓", "user"=>{"user_affiliates"=>{"affiliate_id"=>"1"}}, "commit"=>"Add Affiliate", "id"=>"2"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ app/controllers/users_controller.rb:58
Completed 500 Internal Server Error in 62ms (ActiveRecord: 6.4ms)
ArgumentError (wrong number of arguments (given 0, expected 1..2)):
app/controllers/users_controller.rb:88:in `[]'
app/controllers/users_controller.rb:88:in `user_params'
app/controllers/users_controller.rb:61:in `block in update'
app/controllers/users_controller.rb:60:in `update'
User controller params:
def user_params
params.require(:user).permit(:name, :approved, :seller, :buyer, :admin, :stripe_account, :email, :password, :password_confirmation, :role, :affiliate_id, :affiliate_ids [], :user_affiliates, :commission)
end
Is my form wrong?
I want to be able to list users in a table as a user.admin, have a text field, and enter an affiliate_id, and then have the user_id and affiliate_id inputted into the UserAffiliate table. I also want to be able to add commission rates that both the user.admin and Affiliate can change.
How can I do this correctly?
Update:
I fixed my params but still have errors:
params:
def user_params
params.require(:user).permit(:name, :approved, :seller, :buyer, :admin, :stripe_account, :email, :password, :password_confirmation, :role, :affiliate_id, :user_affiliates, :affiliate, :commission, affiliate_ids: [])
end
Error:
Started PATCH "/users/2" for 127.0.0.1 at 2019-01-10 21:20:53 -0500
Processing by UsersController#update as JS
Parameters: {"utf8"=>"✓", "user"=>{"user_affiliates"=>{"affiliate_id"=>"1"}}, "commit"=>"Add Affiliate", "id"=>"2"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ app/controllers/users_controller.rb:58
Unpermitted parameter: :user_affiliates
(0.5ms) BEGIN
↳ app/controllers/users_controller.rb:61
(0.1ms) ROLLBACK
↳ app/controllers/users_controller.rb:61
Completed 406 Not Acceptable in 21ms (ActiveRecord: 5.3ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/users_controller.rb:60:in `update'
I tried changing it to user_affiliate (non pluar) and plural in all the controller, model, and form. Is there anything i need to do to my update on the users controller?
User Controller update:
def update
#user = User.find(params[:id])
# #affiliate = current_affiliate
respond_to do |format|
if #user.update(user_params) # <- you'll need to define these somewhere as well
if #user.admin?
format.html { redirect_to '/admin/users', notice: "yahoo" }
format.json { render json: #user }
# elsif #affiliate
# format.html { redirect_to '/a/clients', notice: "yahoo" }
# format.json { render json: #user }
else
format.html { render :edit }
format.json { render json: { errors: #user.errors }, status: :unprocessable_entity }
end
end
end

best_in_place nested attribute inline edit throws "204 No Content" error

I'm using the Best In Place Gem to do inline edits on a table of Tasks that has a nested attribute for Storeorder, however when I try to edit a Storeorder attribute using the instructions provided in this post, I get a 204 No Content error thrown at me. I wonder if it has to do with the first transaction beginning before the 'Storeorder Load' happens? In all non-nested BIP updates, it does the UPDATE within the first "begin transaction" call, whereas here it's still loading the Storeorder. The parameters are 100% correct as far as I can tell. See code,
Started PUT "/tasks/3" for 104.200.151.54 at 2017-02-05 18:08:24 +0000
Processing by TasksController#update as JSON
Parameters: {"task"=>{"storeorder_attributes"=>{"id"=>"3", "activity"=>"Shipped"}}, "authenticity_token"=>"D2c3ddoIC220rkPE5i7U+EGiwSrdCq7s8vdFY8VEQTaTMqetuBo8SJX9+Wabl+Bh6A6d49Pt/Omp4E/nq/udQA==", "id"=>"3"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
CACHE (0.0ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
(0.1ms) begin transaction
Storeorder Load (0.2ms) SELECT "storeorders".* FROM "storeorders" WHERE "storeorders"."task_id" = ? LIMIT ? [["task_id", 3], ["LIMIT", 1]]
(0.1ms) commit transaction
(0.1ms) begin transaction
(0.1ms) commit transaction
Completed 204 No Content in 10ms (ActiveRecord: 1.0ms)
tasks_controller.rb -->
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
def update
#task = Task.find(params[:id])
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to #task, notice: 'Task was successfully updated.' }
format.json { respond_with_bip(#task) }
else
format.html { render :edit }
format.json { respond_with_bip(#task) }
end
end
end
private
def set_task
#task = Task.find(params[:id])
end
def task_params
params.require(:task).permit!
end
end
task.rb -->
class Task < ApplicationRecord
has_one :storeorder, :dependent => :destroy
accepts_nested_attributes_for :storeorder, :reject_if => lambda { |a| a[:store_id].blank? }, :allow_destroy => true
end
storeorder.rb -->
class Storeorder < ApplicationRecord
belongs_to :task
end
dashboard.html.erb -->
<td><%= best_in_place task.storeorder, :activity,
url: task_path(task.id),
param: "task[storeorder_attributes][id]=#{task.storeorder.id}&task[storeorder_attributes]",
as: :select,
collection: [["Pending Shipment", "Pending Shipment"], ["Shipped", "Shipped"], ["Cancelled", "Cancelled"], ["Pending Further Action", "Pending Further Action"]], %>
</td>
inner HTML code -->
<span
data-bip-type="select"
data-bip-attribute="activity"
data-bip-collection="[["Pending Shipment","Pending Shipment"],["Shipped","Shipped"],["Cancelled","Cancelled"],["Pending Further Action","Pending Further Action"]]"
data-bip-inner-class="form-control"
data-bip-object="task[storeorder_attributes][id]=3&task[storeorder_attributes]"
data-bip-original-content="Pending Shipment"
data-bip-skip-blur="false"
data-bip-url="/tasks/3"
data-bip-value="Shipped"
class="best_in_place form-control"
id="best_in_place_storeorder_3_activity">
Shipped
</span>
I can't see what I could possibly be missing that causes this error. It's imperative that I'm allowed to do inline edits to keep the workflow consistent, otherwise I'm open to alternative suggestions since I know BIP doesn't have nested attribute editing within their scope by default.
:reject_if => lambda { |a| a[:store_id].blank? }
Don't see any store_id being passed in params.

Rails 4 / Devise Force User to change password on first login

Im having a weird issue trying to force my users to change their passwords on first login.
My server output is telling me it completed the patch successfully, however when I go to log back into the app its still the old password? I'll post output below.
But first here is my code to make this happen:
#application_controller.rb
# Force PW Change On 1st Login
def after_sign_in_path_for(resource)
if current_user.sign_in_count == 1
edit_passwords_path
else
authenticated_root_path
end
end
#passwords_controller.rb
def edit
#user = current_user
end
def update
if current_user.update_without_password(user_params)
flash[:notice] = "Password updated successfully."
redirect_to authenticated_root_path
else
flash[:alert] = "There was a problem, please try again."
render :edit
end
end
private
def user_params
params.require(:user).permit(:password, :password_confirmation)
end
#passwords form_for
<%= form_for current_user, url: passwords_path do |f| %>
password:<br />
<%= f.password_field :password %><br />
password_confirmation:<br />
<%= f.password_field :password_confirmation %><br />
<br />
<%= f.submit %>
<% end %>
#routes.rb
resource :passwords
The force password is doing everything it is supposed to except actually saving the new passwords.
my server output:
Started PATCH "/passwords" for ::1 at 2016-09-07 02:23:43 -0600
Processing by PasswordsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"zUOrOdquBht6uwvjvBkPj2yaO0dCgL+3XGhKo0YV1+W/4rEEiiIRHwwOzRCqvSVeVkAO0M7c73ogcmgNQDq/DQ==", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update User"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.1ms) BEGIN
(0.1ms) COMMIT
Redirected to http://localhost:3000/
Completed 302 Found in 5ms (ActiveRecord: 0.7ms)
Started GET "/" for ::1 at 2016-09-07 02:23:43 -0600
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Processing by WelcomeController#index as HTML
Rendering welcome/index.html.erb within layouts/application
Rendered welcome/index.html.erb within layouts/application (0.4ms)
Rendered layouts/navigation/_unassigned.html.erb (0.5ms)
Rendered layouts/messages/_flash_msg.html.erb (0.5ms)
Completed 200 OK in 56ms (Views: 54.9ms | ActiveRecord: 0.0ms)
In PasswordsController#Update change update_without_password to update_with_password:
def update
if current_user.update_with_password(user_params)
flash[:notice] = "Password updated successfully."
redirect_to authenticated_root_path
else
flash[:alert] = "There was a problem, please try again."
render :edit
end
end

Custom devise update form not saving changes

I have a custom Devise form that I want to update my devise user with. But the from is not saving the changes.
Form:
.small-12.columns
.well
=form_tag(test_registration_path, method: 'PUT', id: "my-awesome-dropzone.dropzone") do
.row
.small-4.columns
%input#photo-dropzone{:name => "file", :type => "file"}/
.small-8.columns
.row
.small-12.columns
= label_tag :name
= text_field_tag :name
= submit_tag "Submit", class: "button button-green"
Log:
Started PUT "/tests" for 127.0.0.1 at 2014-10-06 11:48:04 -0700
Processing by Tests::Devise::RegistrationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"0R7keMt16tsIdjawQHE7yq15Ye6V/w5I4klAvs1WWLY=", "name"=>"testt", "commit"=>"Submit"}
Artist Load (0.4ms) SELECT "artists".* FROM "artists" WHERE "artists"."id" = 19 ORDER BY "artists"."id" ASC LIMIT 1
Artist Load (0.2ms) SELECT "artists".* FROM "artists" WHERE "artists"."id" = $1 LIMIT 1 [["id", 19]]
(0.1ms) BEGIN
(0.1ms) COMMIT
Redirected to http://site.dev/artists/19
Completed 302 Found in 5ms (ActiveRecord: 0.8ms)
RegistrationsController#Update
def update
# For Rails 4
account_update_params = devise_parameter_sanitizer.sanitize(:account_update)
# For Rails 3
# account_update_params = params[:user]
# required for settings form to submit when password is left blank
if account_update_params[:password].blank?
account_update_params.delete("password")
account_update_params.delete("password_confirmation")
end
#user = Test.find(current_test.id)
if #user.update_attributes(account_update_params)
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case their password changed
sign_in #user, :bypass => true
redirect_to artist_path(#user)
else
render "edit"
end
end
What do I have to do to properly update my params?
Did you point devise to your custom controller?
https://github.com/plataformatec/devise/wiki/How-To:-Customize-routes-to-user-registration-pages

Resources