Form_for work but doesn't save into table - ruby-on-rails

I want to make a simple form_forbut that doesn't work fully.
I have two table:
Users -> has_many -> Cvs
this is my form :
<%= form_for(:cvs, action: "create", html: { method: :post }) do |f| %>
Nom : <%= f.text_field :nom %><br />
<%= f.submit %>
<% end %>
In my controller:
def create
#cv = Cv.new(cv_params)
#cv.save
end
With cv_params :
def cv_params
params.require(:cv).permit(:nom)
end
In my route.rb :
post 'createcv' => 'static_pages#createcv'
My controller is static_pages and my view is createcv
The field appear when I load the view, I put something but nothing is create in the table (there is no error). How can I correct that please?
EDIT:
The logs
Started GET "/createcv" for ::1 at 2015-06-16 17:22:03 +0200
Processing by StaticPagesController#createcv as HTML
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Cv Load (0.0ms) SELECT "cvs".* FROM "cvs" WHERE "cvs"."user_id" = ? [["user_id", 1]]
Rendered static_pages/createcv.html.erb within layouts/application (10.0ms)
Rendered layouts/_shim.html.erb (1.0ms)
Rendered layouts/_header.html.erb (2.0ms)
Rendered layouts/_footer.html.erb (1.0ms)
Completed 200 OK in 582ms (Views: 570.6ms | ActiveRecord: 0.0ms)
Started POST "/createcv" for ::1 at 2015-06-16 17:22:12 +0200
Processing by StaticPagesController#createcv as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"28oSelskM87GZ/geLj6yl3tOrtvKktH/poBasO4pyt7I2QNKxw9HX4J+yS3cmisuzmGOGnr+6IxZdh+uQGDRDQ==", "cvs"=>{"nom"=>"hjsvqsv"}, "commit"=>"Save Cvs"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Cv Load (0.0ms) SELECT "cvs".* FROM "cvs" WHERE "cvs"."user_id" = ? [["user_id", 1]]
Rendered static_pages/createcv.html.erb within layouts/application (11.0ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_header.html.erb (1.0ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 643ms (Views: 629.0ms | ActiveRecord: 1.0ms)

params.require(:cv).permit(:nom)
should be
params.require(:cvs).permit(:nom)
cause all params are nested inside :cvs not :cv
also, looking at your logs and route:
Processing by StaticPagesController#createcv
you need to rename your action to createcv.
Anyway, the routing in your app seems to be wrong... Unless you want it that way.
Ideally you should do something like this:
in static_pages controller, action createcv you'll initiate new CV object:
def createcv
...
#cv = Cv.new
end
and in createcv.html.erb the form would be like this:
<%= form_for #cv do |f| %>
Nom : <%= f.text_field :nom %><br />
<%= f.submit %>
<% end %>
rails will know that #cv in the form is a new object, and it will add the proper route to the form, that will point (depending on your app) to /cvs with post method.
That means when you submit the cv, action create from cv_controller should handle the rest of the process.
In this case you won't need the route you added, it should be there after you added
resources :cvs
This is just an example that might not fit your needs, cause I wouldn't know how did you named your models, controllers, etc..

The answer of Rajarshi Das is fine, only it seems to me that you want to open your form by visiting /createcv. so change your routes to:
# routes.rb
get '/createcv', to: 'static_pages#new'
post 'create', to: 'static_pages#create'
# static_pages controller
def new
#cv = Cv.new
end
def create
#cv = Cv.new(cv_params)
if #cv.save
flash[:alert] = 'Cv created!'
else
render 'new'
flash[:alert] = 'Error in form'
end
private
def cv_params
params.require(:cv).permit(:nom) # :cv must be singular
end
# static_pages/new.html.erb view
<%= form_for #cv do |f| %>
<p>
<%= f.label :nom %>
<%= f.text_field :nom %>
</p>
<%= f.submit %>
<% end %>

Related

Rails nested resources redirection after update

Good day all, I'm pulling my hair out on this one, I've seen similar posts but none of them get me in the direction I'm trying to go.
That said, I've got a pretty complex app that's relying heavily on nested resources and name-spacing, when I save a record it saves perfectly
and redirects correctly. When I update that same record the URL changes but not as I would expect. I understand the flow from edit to update and
the set_input call pulling the params[:id], what I don't understand is why the URL is changing the parents resource to reflect the record ID.
/servers/1/features/rsyslog_inputs/12/edit"
changes to the following after update
/servers/12/features/rsyslog_inputs/12/edit"
LOGS
Started GET "/servers/1/features/rsyslog_inputs/12/edit" for 127.0.0.1 at 2017-12-08 12:27:55 -0600
Processing by Features::RsyslogInputsController#edit as HTML
Parameters: {"server_id"=>"1", "id"=>"12"}
RsyslogInput Load (0.6ms) SELECT "rsyslog_inputs".* FROM "rsyslog_inputs" WHERE "rsyslog_inputs"."id" = $1 LIMIT $2 [["id", 12], ["LIMIT", 1]]
Rendering features/rsyslog_inputs/edit.html.erb within layouts/application
Rendered shared/_error_messages.html.erb (0.4ms) [cache miss]
Rendered features/rsyslog_inputs/_form.html.erb (4.3ms) [cache miss]
Rendered features/rsyslog_inputs/edit.html.erb within layouts/application (6.5ms)
Rendered layouts/_shim.html.erb (0.5ms) [cache miss]
User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Rendered layouts/_navbar_top.html.erb (0.9ms) [cache miss]
Rendered layouts/_navbar_side.html.erb (0.5ms) [cache miss]
Completed 200 OK in 90ms (Views: 84.7ms | ActiveRecord: 1.7ms)
Here the PATCH has modified the servers/:id to reflect the id of the rsyslog_inputs and not retained its "1" as shown above
Started PATCH "/servers/12/features/rsyslog_inputs/12" for 127.0.0.1 at 2017-12-08 12:27:58 -0600
Processing by Features::RsyslogInputsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"dFt61NcQWXoKpmScrkngT47ZxDdhzMUcCyJ5fZKrdbaOVqKfLXMVeBUj20zKKHQ8wGe4fi2QEw98cLviyO4wQw==", "rsyslog_input"=>{"inputs_interface"=>"eth04", "inputs_ip_address"=>"1.1.1.1", "inputs_input_type"=>"tcp", "inputs_port_number"=>"22", "inputs_input_name"=>"test02", "inputs_tls"=>"0"}, "commit"=>"Save Input", "appliance_id"=>"12", "id"=>"12"}
RsyslogInput Load (0.7ms) SELECT "rsyslog_inputs".* FROM "rsyslog_inputs" WHERE "rsyslog_inputs"."id" = $1 LIMIT $2 [["id", 12], ["LIMIT", 1]]
(0.6ms) BEGIN
Server Load (1.0ms) SELECT "servers".* FROM "servers" WHERE "servers"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
SQL (1.0ms) UPDATE "rsyslog_inputs" SET "inputs_interface" = $1, "updated_at" = $2 WHERE "rsyslog_inputs"."id" = $3 [["inputs_interface", "eth04"], ["updated_at", "2017-12-08 18:27:58.904817"], ["id", 12]]
(0.8ms) COMMIT
Redirected to http://localhost:3000/servers/12/features/rsyslog_inputs
Completed 302 Found in 12ms (ActiveRecord: 4.0ms)
Controller
class Features::RsyslogInputsController < ApplicationController
before_action :set_input, only: [:show, :edit, :update, :destroy]
def index
# Let's search for all inputs associated with the corresponding appliance
#inputs = RsyslogInput.where(server_id: params[:server_id])
end
def create
#input = RsyslogInput.new(input_params)
#input.build_server
#input.server_id = params[:server_id]
if #input.save
flash[:notice] = "Input was successfully saved."
redirect_to server_features_rsyslog_inputs_path
else
render('new')
end
end
def destroy
if #input.destroy
flash[:notice] = "Input was successfully destoryed."
redirect_to server_features_rsyslog_inputs_path
else
flash[:alert] = "Unable to destroy #{#input.inputs_input_name}"
end
end
def update
if #input.update(input_params)
flash[:notice] = "Input was successfully updated"
redirect_to server_features_rsyslog_inputs_path
else
render('edit')
end
end
def new
#input = RsyslogInput.new
end
def edit; end
def show ;end
private
def set_input
#input = RsyslogInput.find(params[:id])
end
def input_params
params.require(:rsyslog_input).permit(:inputs_interface,
:inputs_input_type,
:inputs_ip_address,
:inputs_port_number,
:inputs_input_name,
:inputs_tls,
:server_id)
end
end
Form
<%= form_for ([:server, :features, #input]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<br/>
<div class="form-group clients-form-container">
<%= f.label :inputs_interface, 'Input interface:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_interface, class: 'form-control', placeholder: 'Enter Interface: (e.g. eth0)' %>
</div>
<br/>
<%= f.label :inputs_ip_address, 'Input IP Address:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_ip_address, class: 'form-control', placeholder: 'Enter IP Address:' %>
</div>
<br/>
<%= f.label :inputs_input_type, 'Input type:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_input_type, class: 'form-control', placeholder: 'TCP/UDP' %>
</div>
<br/>
<%= f.label :inputs_port_number, 'Input port number:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_port_number, class: 'form-control', placeholder: 'Enter Port:' %>
</div>
<br/>
<%= f.label :inputs_input_name, 'Input Name:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_input_name, class: 'form-control', placeholder: 'Enter Ruleset Name)' %>
</div>
<br/>
<div class="form-inline">
<%= f.label :inputs_tls, 'Enable TLS:', class: 'col-1 col-form-label' %>
<div class="col-3">
<%= f.check_box :inputs_tls, class: 'form-control check-box-alignment' %>
</div>
</div>
</div>
<%= f.submit 'Save Input', class: 'btn btn-primary btn-lg' %>
<%= link_to 'Cancel', :back, class: 'btn btn-secondary region-btn btn-lg' %>
<% end %>
<br/>
Routes
resources :servers do
namespace :features do
resources :rsyslog_inputs
resources :rsyslog, only: :index
end
end
server_features_rsyslog_inputs GET /servers/:server_id/features/rsyslog_inputs(.:format) features/rsyslog_inputs#index
POST /servers/:server_id/features/rsyslog_inputs(.:format) features/rsyslog_inputs#create
new_server_features_rsyslog_input GET /servers/:server_id/features/rsyslog_inputs/new(.:format) features/rsyslog_inputs#new
edit_server_features_rsyslog_input GET /servers/:server_id/features/rsyslog_inputs/:id/edit(.:format) features/rsyslog_inputs#edit
server_features_rsyslog_input GET /servers/:server_id/features/rsyslog_inputs/:id(.:format) features/rsyslog_inputs#show
PATCH /servers/:server_id/features/rsyslog_inputs/:id(.:format) features/rsyslog_inputs#update
PUT /servers/:server_id/features/rsyslog_inputs/:id(.:format) features/rsyslog_inputs#update
DELETE /servers/:server_id/features/rsyslog_inputs/:id(.:format) features/rsyslog_inputs#destroy
server_features_rsyslog_index GET /servers/:server_id/features/rsyslog_inputs(.:format) features/rsyslog_inputs#index
seeing your forms, controller and the requirement, i would advice that you use the route helpers and pass in the appropriate parameters there
like in your form explicitly set the form url to
server_features_rsyslog_input(server_id: params[:server_id], id: #input.id)
and in your controller too pass in the parameters explicitly
So this actually turned out to be a redirection issue in the update method. I wasn't specifying the server_id which wouldn't allow the redirection back to the index based on the server.

Rails, cant get update to work with cocoon when removing attribute "undefined method '[]' for nil:NilClass"?

I am wondering if someone could tell me why I am getting this error "undefined method '[]' for nil:NilClass". This happens when I remove a picture with cocoon and try update. The method works fine for adding pictures to the edited gallery but I am getting this error when removing and updating. I tried using unless #pictures.blank? end I am assuming the problem is when cocoon removes the picture but I am not sure what to do from there. the server error is,
Started PATCH "/galleries/41" for ::1 at 2017-05-07 16:03:02 +1000
Processing by GalleriesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"cG1UXCvODhYzqqAr++EAn8GvMVk7+t/eASkzDDOoPmJfw3l6ax/F2xXMhvs7FcrJ3LOuTd0sks5+2fb86kQv0Q==", "gallery"=>{"name"=>"Hellooo", "cover"=>"123456", "pictures_attributes"=>{"0"=>{"_destroy"=>"1", "id"=>"47"}, "1"=>{"_destroy"=>"1", "id"=>"48"}}}, "commit"=>"Update Gallery", "id"=>"41"}
Gallery Load (0.0ms) SELECT "galleries".* FROM "galleries" WHERE "galleries"."id" = ? LIMIT ? [["id", 41], ["LIMIT", 1]]
Unpermitted parameter: pictures_attributes
(0.0ms) begin transaction
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.0ms) commit transaction
Completed 500 Internal Server Error in 4ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `[]' for nil:NilClass):
...
Perhaps if someone could explain this to me would be great!
_form.html.erb
<%= form_for(#gallery, multipart: true) do |f| %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :cover %>
<%= f.text_field :cover %>
</div>
<div id="pictures">
<%= f.fields_for :pictures do |pic| %>
<%= render 'picture_fields', f: pic %>
</div>
<% end %>
<div class="links">
<%= link_to_add_association 'add picture', f, :pictures %>
<%= f.submit %>
</div>
<% end %>
_picture_fields.html.erb
<div class="nested-fields">
<div class="field">
<%= f.label :picture %>
<%= f.file_field :picture, multiple: true, name: "pictures[picture][]" %>
<%= link_to_remove_association "remove picture", f %>
</div>
</div>
GalleriesController
def update
#gallery = Gallery.find(params[:id])
if #gallery.update(gallery_params)
params[:pictures][:picture].each do |pic|
#pictures = #gallery.pictures.create!(picture: pic)
end
flash[:success] = "Gallery Updated!"
redirect_to root_url
else
render 'edit'
end
end
Edit: Added gallery_params
def gallery_params
params.require(:gallery).permit(:id, :name, :user_id, :cover, picture_attributes: [:id, :gallery_id, :picture, :_destroy])
end
EDIT: Added create action and server log using cocoon
def create
#user = User.first
#gallery = #user.galleries.build(gallery_params)
if #gallery.save
flash[:success] = "Picture created!"
redirect_to root_url
else
render 'new'
end
end
server log
Started POST "/galleries" for ::1 at 2017-05-10 13:18:43 +1000
Processing by GalleriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XU3z2jMdbselPJZ2SdZdGPwiAebiPznt8GWRqmbv8LM/MIxO+sNo1z2NTaDQ3nJNm0qaBJ66ny5254MPpHZaQQ==", "gallery"=>{"name"=>"Hello", "cover"=>"123456", "pictures_attributes"=>{"1494386318553"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xac59228 #tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170510-7596-16xlrir.jpg>, #original_filename="Skateboard 1.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"gallery[pictures_attributes][1494386318553][picture]\"; filename=\"Skateboard 1.jpg\"\r\nContent-Type: image/jpeg\r\n">, "_destroy"=>"false"}, "1494386321001"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xac59150 #tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170510-7596-jxo0st.jpg>, #original_filename="Skateboard 2.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"gallery[pictures_attributes][1494386321001][picture]\"; filename=\"Skateboard 2.jpg\"\r\nContent-Type: image/jpeg\r\n">, "_destroy"=>"false"}}}, "commit"=>"Create Gallery"}
User Load (0.0ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]]
(0.0ms) begin transaction
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.0ms) rollback transaction
Rendering galleries/new.html.erb within layouts/application
Rendered galleries/_picture_fields.html.erb (1.0ms)
Rendered galleries/_picture_fields.html.erb (0.5ms)
Rendered galleries/_picture_fields.html.erb (0.5ms)
Rendered galleries/_form.html.erb (42.0ms)
Rendered galleries/new.html.erb within layouts/application (58.5ms)
Completed 200 OK in 157ms (Views: 139.3ms | ActiveRecord: 0.0ms)
Mmmm. Confused. There is no params[:pictures] so that is obviously nil (check the log you posted at the top). So that is causing the error. If you are looking for the pictures posted, you should refer to params[:pictures_attributes], but not even sure what you are trying to do there: create an empty picture (again?) for each posted pictures? The pictures are saved by doing the gallery.update(gallery_params).
Note: iterating over the posted params is imho definitely wrong, because if one is deleted, it will still be posted with the nested parameter _destroy set to true, so it can be deleted correctly from the database, or if a picture already existed, it will also be posted again (and not saved, since it already exists).
[EDIT] Add short solution:
use f.fields_for :pictures in your view: this will iterate over the existing pictures a gallery has, and will allow to delete/edit existing, and add new pictures to a gallery
fix your gallery_params and allow pictures_attributes (instead of the singular form)(otherwise nothing is saved)
in your controller just write #gallery.update_attributes(gallery_params) and do not iterate over params[:pictures] at all (remove that part) and it should just work (because the update_attributes will already have done this, at least if you want to iterate manually use pictures_attributes)
It looks like your gallery_params method is not permitting your pictures_attributes. You didn't post that code but I noticed in the error log Unpermitted parameter: pictures_attributes which means that your strong parameters(the gallery_params method) is filtering those parameters out.
Basically the whole point of the strong parameters is to make sure that you only pass through keys that you actually want to get passed through. So your controller is like "Nobody told me I am supposed to accecpt picture_attributes so I won't allow them through." Then your code is expecting there to be a picture object in the pictures array, but the pictures array doesn't have the picture object causing an error.
Can you post the code for gallery params? Can you also post the contents of params? Full disclosure: I don't really know rails 5 so there could be some other stuff going on.

ActionController::UnknownFormat Error for only format.js

I am simply using -
respond_to do |format|
format.js
end
in my create action. Don't know why but i am getting an the UnknownFormat error. The error is gone if i put in both "format.html" and "format.js". But i want to stay in the same page and make an ajax call. I have gone through like 5 pages of google search results for every possible search and still nothing works for me. Can anyone help me out here?
My form is like this -
<%= form_for [:home, Photo.new], remote: true, :html => {:id => "new-photo-form"} do |f| %>
<div id="upload-field">
<%= f.file_field :image %>
</div>
<%= f.hidden_field :album_id, :value => album.id %>
<div id="photo-add-link">
<%= link_to 'Add Selected Images', '#', remote: true, :onclick => "$('#new-photo-form').submit()" %>
</div>
<% end %>
server logs -
Started POST "/home/photos" for 127.0.0.1 at 2016-12-28 08:23:38 +0530
Processing by Home::PhotosController#create as HTML
Parameters: {"utf8"=>"✓", "photo"=>{"image"=># <ActionDispatch::Http::UploadedFile:0x007fd5541a0578 #tempfile=# <Tempfile:/tmp/RackMultipart20161228-6069-175ahz0.jpg>, #original_filename="emilia-clark.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"photo[image]\"; filename=\"emilia-clark.jpg\"\r\nContent-Type: image/jpeg\r\n">, "album_id"=>"68"}}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Completed 406 Not Acceptable in 2ms (ActiveRecord: 0.1ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/home/photos_controller.rb:11:in `create'
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (3.4ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.7ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.8ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/actionpack- 4.2.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (16.2ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.3ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.2ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.4ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (1.2ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (16.2ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.2ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.4ms)
Rendered /home/santhosh/.rvm/gems/ruby-2.3.0/gems/web-console- 2.3.0/lib/web_console/templates/index.html.erb (29.5ms)
I noticed that you are using a file_field in your form. JavaScript doesn't have access to your filesystem, so you can't create an ajax request to upload files. There are some gems to workaround this. check this gem.

Bringing Form Values into a Controller - Ruby on Rails

I am trying to create a basic form where the user can change their password but needs to enter their old password in order to do it. I am having trouble verifying the user's old password. Everytime I enter an old password it says password doesn't match when I know that it does. If a replace the actual password in the authenticate field it works. How can I bring in what was entered in the form to verify the old password that was entered?
Form:
<%= form_for(#user, :url => change_password_action_path(current_user.id), html: { "role" => "form" }) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="form-group">
<%= f.label :old_password, "Old Password:", :class => "control-label" %>
<%= f.password_field :old_password, :class => "form-control" %>
</div>
<div class="form-group">
<%= f.label :password, "New Password:", :class => "control-label" %>
<%= f.password_field :password, :class => "form-control" %>
</div>
<div class="form-group">
<%= f.label :password_confirmation, "Password Confirmation:", :class => "control-label" %>
<%= f.password_field :password_confirmation, :class => "form-control" %>
</div>
<%= f.submit "Update Password", class: "btn btn-large btn-primary" %>
Controller
def change_password
#user = User.find(current_user.id)
end
def change_password_action
user = current_user.id
if User.find(user).authenticate(params[:old_password]) == false
flash[:danger] = "Password Doesnt Match: "
else
flash[:success] = "Password Match"
# Validate the new and confirm password.
end
redirect_to action: :change_password
end
Routes
get '/change_password' => 'main#change_password'
patch '/change_password_action' => 'main#change_password_action'
Rails Server Logs
Started PATCH "/change_password_action.1" for 127.0.0.1 at 2014-01-15 09:04:38 -0600
Processing by MainController#change_password_action as
Parameters: {"utf8"=>"✓", "authenticity_token"=>"yYdUx37Q7alr3SccuMVjPwCJoMgMPOaiKTesSsILlP4=", "user"=>{"old_password"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Update Password"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'fc1baf63bac072bfefd5ed27664ece5427ad9e64' LIMIT 1
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"yYdUx37Q7alr3SccuMVjPwCJoMgMPOaiKTesSsILlP4=", "user"=>{"old_password"=>"test123", "password"=>"", "password_confirmation"=>""}, "commit"=>"Update Password", "controller"=>"main", "action"=>"change_password_action", "format"=>"1"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Redirected to http://localhost:3000/change_password
Completed 302 Found in 115ms (ActiveRecord: 0.7ms)
Started GET "/change_password" for 127.0.0.1 at 2014-01-15 09:04:39 -0600
Processing by MainController#change_password as HTML
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" = 'fc1baf63bac072bfefd5ed27664ece5427ad9e64' LIMIT 1
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Rendered shared/_error_messages.html.erb (0.1ms)
Rendered main/change_password.html.erb within layouts/application (2.6ms)
Rendered layouts/_header.html.erb (0.5ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 19ms (Views: 16.2ms | ActiveRecord: 0.4ms)
It looks like you're passing the wrong parameter into your authenticate method.
Try using params[:user][:old_password] instead of params[:old_password].
The param value you want will be under the :user key, because your form_for is using a user object.
You can also see this in your server logs where the user param in your params hash is:
"user"=>{"old_password"=>"[FILTERED]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}

form_for filter query directing to create action

Afternoon All,
I'm trying to put a filter in my rails application but when I process the below it redirects to the create action on submit and I cannot figure out why it would pass to this action:
jobs_controller.rb
def index
#jobs = Job.all
#show_sub_nav = true
#lang = Job.find_by_sql("SELECT languages FROM jobs GROUP BY languages").map &:languages
#list = params[:languages].blank? ? Job.all : Job.find_all_by_category(params[:languages])
end
my view
<%= form_tag(jobs_path :method => 'get', :action => 'index') do %>
<%= select_tag "languages", options_for_select(#lang) %>
<%= submit_tag "Filter" %>
<% end %>
I was playing around the the form_for() with different options but it doesn't seem to make any difference and here is the log on click:
Started POST "/jobs?method=get" for 127.0.0.1 at 2013-12-16 19:35:54 +0000
Processing by JobsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p34KrqtWpFr5xCAB+leP3YkVbJjLpDKix4BJDUZquAg=", "languages"=>"Ratke-Beatty", "commit"=>"Filter", "method"=>"get"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendered jobs/_subregion_select.html.erb (0.1ms)
Rendered jobs/_form.html.erb (38.7ms)
Rendered jobs/new.html.erb within layouts/application (39.9ms)
Rendered layouts/_navbar.html.erb (0.5ms)
Completed 200 OK in 75ms (Views: 54.2ms | ActiveRecord: 0.8ms)
It redirects because you're setting the http type to GET with this: :method => 'get'.
Generally, forms POST data so you either want :method => 'post', or if you're following the restful routes design, you don't need to specify the :method as rails is smart enough to know.
Solved it with the following:
<%= form_tag({ :action => "index"}, { :method => "get"}) do %>
Seems to work and gives me the right output.

Resources