I am currently stuck with the search function for blog post.
Controller and html rendering seemed to work well, but I couldn't see any update from browser, Chrome.
From the start of searching scenario, it goes to _navbar.html.erb as below
<%= form_with url: admin_posts_path, method: "get" do %>
<%= text_field_tag :search, params[:search], id: "input-search", placeholder: "Search Posts" %>
<% end %>
, and it goes to posts_controller.rb as below
def index
if params[:search]
#posts = Post.search(params[:search]).all.order('created_at DESC').paginate(per_page: 3, page: params[:page])
puts "&&&&&&&&&&&&&&&&&"
p #posts
puts "###################"
else
#posts = Post.all.order('created_at DESC').paginate(per_page: 3, page: params[:page])
end
end
I found the value of #posts got the right result by using puts through the server log.
However, finally after rendering index.html.erb as below, browser doesn't update any rendered html at all. It just stayed as the current page.
<div class="main">
<section>
<button class="create-button">Create New</button>
<% if #posts.exists? %>
<% #posts.each do |post| %>
<article class="article-summary">
<h1 class="article-title"><%= post.title %></h1>
<p class="article-content"><%= truncate post.body, length: 200 %></p>
<p class="article-created-at"><%= post.created_at.to_time.strftime('%B %e at %l:%M %p') %></p>
<p class="article-command"><button>Edit</button> <%= link_to button_tag("Delete"), admin_post_path(post), method: :delete, data: { confirm: 'Are you sure?' } %></p>
<%= image_tag 'https://placekitten.com/1000/400', class: "article-image" %>
</article>
<% end %>
<%= will_paginate #posts, class: "page"%>
<% else %>
<h2>There is no post</h2>
<% end %>
</section>
</div>
When I saw the server log, it definitely rendered the search results, but I don't have any idea why the browser screen doesn't change anything.
This is the server log
Started GET "/admin/posts?search=nine" for ::1 at 2020-04-29 00:03:15 +1000
Processing by Admin::PostsController#index as JS
Parameters: {"search"=>"nine"}
&&&&&&&&&&&&&&&&&
Post Load (1.1ms) SELECT "posts".* FROM "posts" WHERE (title like '%nine%' OR body like '%nine%') ORDER BY created_at DESC LIMIT $1 OFFSET $2 [["LIMIT", 3], ["OFFSET", 0]]
↳ app/controllers/admin/posts_controller.rb:45:in `p'
#<ActiveRecord::Relation [#<Post id: 9, title: "Blog Post nine", category_id: 1, user_id: 3, tags: "rails", image: nil, body: "Lorem ipsum dolor sit amet, consectetur adipiscing...", created_at: "2020-04-28 12:41:46", updated_at: "2020-04-28 12:41:46">]>
###################
Rendering admin/posts/index.html.erb within layouts/admin/application
Post Exists? (0.4ms) SELECT 1 AS one FROM "posts" WHERE (title like '%nine%' OR body like '%nine%') LIMIT $1 OFFSET $2 [["LIMIT", 1], ["OFFSET", 0]]
↳ app/views/admin/posts/index.html.erb:4
CACHE Post Load (0.0ms) SELECT "posts".* FROM "posts" WHERE (title like '%nine%' OR body like '%nine%') ORDER BY created_at DESC LIMIT $1 OFFSET $2 [["LIMIT", 3], ["OFFSET", 0]]
↳ app/views/admin/posts/index.html.erb:5
Rendered admin/posts/index.html.erb within layouts/admin/application (Duration: 4.4ms | Allocations: 1640)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered partials/_navbar.html.erb (Duration: 0.9ms | Allocations: 909)
Rendered partials/_footer.html.erb (Duration: 0.2ms | Allocations: 75)
Completed 200 OK in 28ms (Views: 15.6ms | ActiveRecord: 1.5ms | Allocations: 14931)
Searching image
#Adwaith gave me the solution.
local: true for the form_with tag really worked for me as below.
<%= form_with url: admin_posts_path, local: true, method: "get" do %>
<%= text_field_tag :search, params[:search], id: "input-search", placeholder: "Search Posts" %>
<% end %>
Thanks #Adwaith
Related
I'm sure this should be simple and I'm overlooking something daft.
Rails 6.1.1
Ruby 3.0.0
I'm using active storage to attach multiple 'photos' to my Articles model.
In Articles 'show.html.erb' I want to place the photos in a number of different places in the article, not looping all of them in a row in the same place.
show.html.erb
<% #first2photos.each do |article| %>
<%= image_tag(article.photos) %>
<% end %>
articles.controller.erb
def show
#first2photos = Article.order("created_at DESC").first(2)
end
This gives the following error:
Can't resolve image into URL: undefined method `to_model' for #<ActiveStorage::Attached::Many:0x00007fdbbfa852a8 #name="photos", #record=#<Article id: 1, title: "This is the first post", snippet: "Hopefully this will also attach a couple of photos", body: "Nullam ac odio eget mauris accumsan malesuada. Nul...", created_at: "2021-01-30 20:50:31.766713000 +0000", updated_at: "2021-01-30 21:04:09.424224000 +0000">> Did you mean? to_yaml
If I loop on 'photo's with:
<% #first2photos.each do |photos| %>
<%= image_tag(#article.photos) %>
<% end %>
I still get the following error:
Can't resolve image into URL: undefined method `to_model'...
Changing that to:
<% #first2photos.each do |photos| %>
<%= image_tag(photos) %>
<% end %>
The page now loads, but shows a broken image icon, with no error. Checking the log in Terminal, I'm not sure I can see where it's attempting to access the photo.
Started GET "/articles/1" for ::1 at 2021-01-31 20:56:58 +0000
Processing by ArticlesController#show as HTML
Parameters: {"id"=>"1"}
Article Load (2.9ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/articles_controller.rb:64:in `set_article'
Article Load (1.4ms) SELECT "articles".* FROM "articles" ORDER BY created_at DESC LIMIT $1 [["LIMIT", 2]]
↳ app/controllers/articles_controller.rb:11:in `show'
Rendering layout layouts/application.html.erb
Rendering articles/show.html.erb within layouts/application
Rendered articles/show.html.erb within layouts/application (Duration: 0.4ms | Allocations: 155)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layout layouts/application.html.erb (Duration: 8.6ms | Allocations: 4208)
Completed 200 OK in 20ms (Views: 9.3ms | ActiveRecord: 4.4ms | Allocations: 6022)
You need to loop over the photos collection to use image_tag for each photo.
<% #first2photos.each do |article| %>
<% article.photos.each do |photo|
<%= image_tag(photo) %>
<% end %>
<% end %>
If you want to show only one image per article then:
<% #first2photos.each do |article| %>
<%= image_tag(article.photos.first) %>
<% end %>
I would change the name first2photos to first2articles to make it less confusing too.
I'm developing an application which uses CarrierWave as file manager (upload and download). It's used on my project model. It's kinda working because it upload the file but it doesn't refresh page nor show errors if there is any (but showed in the console -- whitelist error), in the other case (detroy) it shows the message correctly. I'll be really appreciated if you guys help me because i tested several things (redirect to root, etc) and nothing happens.
Project.rb
class Project < ApplicationRecord
mount_uploaders :attachments, AttachmentUploader # Tells raisl to use this uploader with this model
serialize :attachments, JSON # If you use SQLite, add this line.
end
attachments_controller.rb
class AttachmentsController < ApplicationController
before_action :set_project
def create
add_more_attachments(attachments_params[:attachments])
respond_to do |format|
if #project.save
format.html { redirect_to project_path(#project), notice: 'Archivo fue subido existosamente.' }
else
format.html { render partial: 'projects/uploads/new' }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
def download
path = "uploads/#{params[:id]}/#{params[:basename]}.#{params[:extension]}"
send_file path, :x_sendfile=>true
end
def destroy
remove_attachments_at_index(params[:id].to_i)
respond_to do |format|
format.html { redirect_to project_path(#project), notice: 'Archivo fue eliminado existosamente.' }
end
end
private
def set_project
#project = Project.find_by_id(params[:project_id])
end
def add_more_attachments(new_attachments)
attachments = #project.attachments # copy the old images
attachments += new_attachments # concat old images with new ones
#project.attachments = attachments # assign back
end
def remove_attachments_at_index(index)
if #project.attachments.count == 1
#truco para remover ultimo elemento
#project.remove_attachments!
else
remain_attachments = #project.attachments # copy the array
deleted_attachment = remain_attachments.delete_at(index) # delete the target image
#project.attachments = remain_attachments # re-assign back
end
#project.save
end
def attachments_params
params.require(:project).permit({attachments: []}) # allow nested params as array
end
end
Projects#Show (where i upload and remove files)
<div class="medium-8 columns">
<h3>
Archivos
</h3>
<ul>
<% if #project.attachments.present? %>
<% #project.attachments.each_with_index do |attachment,index| %>
<li>
<%= link_to "Descargar #{attachment.file.filename}", "/uploads/#{#project.id}/#{File.basename(attachment.url)}"%>
</li>
<%= link_to "Eliminar", project_attachment_path(#project, index), :method => :delete, data: { confirm: "¿Está seguro de eliminar este archivo?" } %>
<% end %>
<% end %>
</ul>
<%= render(:partial => 'projects/uploads/new') %>
</div>
_new.html.erb (attachment form)
<div class="">
<%= form_with(model: #project, :html => {multipart: true}, url: project_attachments_path(#project), method: :post) do |form| %>
<% if #project.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% #project.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.label :attachments %>
<%= form.file_field :attachments, multiple: true %>
<%= form.submit "Subir", :class => "button" %>
<% end %>
</div>
Console output
Started POST "/projects/3/attachments" for 127.0.0.1 at 2018-03-25 11:51:26 -0300
Processing by AttachmentsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LW7yFaDtZqPSglxM8TSHy2FLBPIrhSl8Gn9rOkZheOWPlj6QDrGOPATlYOj2uQ5exMHp+T+iPbB8lehjY/IzqA==", "project"=>{"attachments"=>[#<ActionDispatch::Http::UploadedFile:0x007fecafc5b900 #tempfile=#<Tempfile:/tmp/RackMultipart20180325-24920-hgufys.pdf>, #original_filename="CAMBIO_ACUMULADOR_RADISSON(1).pdf", #content_type="application/pdf", #headers="Content-Disposition: form-data; name=\"project[attachments][]\"; filename=\"CAMBIO_ACUMULADOR_RADISSON(1).pdf\"\r\nContent-Type: application/pdf\r\n">]}, "commit"=>"Subir", "project_id"=>"3"}
Project Load (0.4ms) SELECT `projects`.* FROM `projects` WHERE `projects`.`id` = 3 LIMIT 1
(0.2ms) BEGIN
Estimate Load (0.4ms) SELECT `estimates`.* FROM `estimates` WHERE `estimates`.`id` = 3 LIMIT 1
SQL (0.6ms) UPDATE `projects` SET `attachments` = '[\"CV_Rodrigo_Cordova.pdf\",\"CAMBIO_ACUMULADOR_RADISSON_1_.pdf\"]', `updated_at` = '2018-03-25 11:51:26' WHERE `projects`.`id` = 3
(2.1ms) COMMIT
Redirected to http://localhost:3000/projects/3
Completed 302 Found in 16ms (ActiveRecord: 3.7ms)
And then... start get but no difference in browser, except when i refresh manually
Started GET "/projects/3" for 127.0.0.1 at 2018-03-25 11:51:26 -0300
Processing by ProjectsController#show as JS
Parameters: {"id"=>"3"}
Project Load (0.5ms) SELECT `projects`.* FROM `projects` WHERE `projects`.`id` = 3 LIMIT 1
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
User Load (0.5ms) SELECT `users`.* FROM `users` INNER JOIN `projects_users` ON `users`.`id` = `projects_users`.`user_id` WHERE `projects_users`.`project_id` = 3
Rendering projects/show.html.erb within layouts/application
Estimate Load (0.4ms) SELECT `estimates`.* FROM `estimates` WHERE `estimates`.`id` = 3 LIMIT 1
(0.4ms) SELECT COUNT(*) FROM `tasks` WHERE `tasks`.`project_id` = 3 AND `tasks`.`status` = 0
(0.4ms) SELECT COUNT(*) FROM `tasks` WHERE `tasks`.`project_id` = 3 AND `tasks`.`status` = 1
(0.4ms) SELECT COUNT(*) FROM `tasks` WHERE `tasks`.`project_id` = 3 AND `tasks`.`status` = 2
(0.3ms) SELECT COUNT(*) FROM `tasks` WHERE `tasks`.`project_id` = 3 AND `tasks`.`status` = 3
Rendered projects/uploads/_new.html.erb (1.9ms)
User Load (0.4ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
Rendered projects/show.html.erb within layouts/application (15.3ms)
Rendered layouts/_navigation_links.html.erb (0.4ms)
Rendered layouts/_nav_links_for_auth.html.erb (1.1ms)
Rendered layouts/_navigation.html.erb (9.8ms)
Rendered layouts/_messages.html.erb (0.4ms)
Rendered layouts/_footer.html.erb (0.7ms)
Completed 200 OK in 139ms (Views: 124.5ms | ActiveRecord: 3.7ms)
EDIT:
Submit button but no change on listed files
Manually refresh (it works!)
Thanks in advance.
where is your image div?
<div class="medium-8 columns">
<h3>
Archivos
</h3>
<ul>
<% if #project.attachments.present? %>
<% #project.attachments.each_with_index do |attachment,index| %>
<li>
<%= link_to "Descargar #{attachment.file.filename}", "/uploads/#{#project.id}/#{File.basename(attachment.url)}"%>
</li>
<%= link_to "Eliminar", project_attachment_path(#project, index), :method => :delete, data: { confirm: "¿Está seguro de eliminar este archivo?" } %>
<% end %>
<% end %>
</ul>
<%= render(:partial => 'projects/uploads/new') %>
</div>
something like this
<%= image_tag attachment.url %>
but you say it works on refesh?
I found the solution. The form was being submitted by ajax.
So i had to add to my form local: true parameter, like this:
<%= form_with(model: #project,local: true, :html => {multipart: true}, url: project_attachments_path(#project), method: :post) do |form| %>
...
<% end %>
And works like a charm.
Thanks to the readers.
I'm trying to display images on the homepage with paperclip and I have unpermitted params and a routing error. I have tried various solutions including trying to pass in an array but I think this is happening because of my own lack of knowledge about rails.
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Hdw1RzedMZdUE0cPrAXz0fkctQKfW9HX3S5ZwYh4lr0PwTJhHhVwcrglJv5qrMQF3T5YkcJZ9zBiRRRlCoNCNQ==", "document"=>{"doc"=>[#<ActionDispatch::Http::UploadedFile:0x007feaf2db80f0 #tempfile=#<Tempfile:/var/folders/1q/zfrk5kxj1015crsc13jwwrz40000gp/T/RackMultipart20170608-15326-1pcmtgl.jpg>, #original_filename="P1150645.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"document[doc][]\"; filename=\"P1150645.jpg\"\r\nContent-Type: image/jpeg\r\n">]}, "commit"=>"Upload Document"}
Unpermitted parameter: doc
(1.9ms) begin transaction
SQL (2.0ms) INSERT INTO "documents" ("created_at", "updated_at") VALUES (?, ?) [["created_at", 2017-06-08 04:47:55 UTC], ["updated_at", 2017-06-08 04:47:55 UTC]]
(0.8ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 46ms (ActiveRecord: 4.8ms)
Started GET "/" for ::1 at 2017-06-08 12:47:55 +0800
Processing by PagesController#home as HTML
User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 3], ["LIMIT", 1]]
User Load (0.3ms) SELECT "users".* FROM "users" LIMIT ? [["LIMIT", 1]]
Rendering pages/home.html.erb within layouts/application
Document Load (3.1ms) SELECT "documents".* FROM "documents" ORDER BY created_at
Rendered documents/_documents.html.erb (56.7ms)
Rendered documents/_new.html.erb (4.2ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE ("users"."id" != 3)
Conversation Load (0.2ms) SELECT "conversations".* FROM "conversations" WHERE (conversations.sender_id = 3 OR conversations.recipient_id = 3)
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.2ms) SELECT COUNT(*) FROM "messages" WHERE "messages"."conversation_id" = ? [["conversation_id", 4]]
Rendered conversations/_index.html.erb (18.5ms)
Rendered pages/home.html.erb within layouts/application (141.2ms)
Rendered shared/_navbar.html.erb (5.2ms)
Completed 200 OK in 426ms (Views: 401.3ms | ActiveRecord: 6.2ms)
Started GET "/docs/original/missing.png" for ::1 at 2017-06-08 12:47:56 +0800
ActionController::RoutingError (No route matches [GET] "/docs/original/missing.png"):
I've tried nesting the params given that document => doc is passing to an array, even if I leave the params blank it still uploads to the database with null fields and routing error, DocumentsController:
def doc_params
params.require(:document).permit(:id, :doc)
end
I've tried multiple validations in here:
class Document < ApplicationRecord
has_attached_file :doc
do_not_validate_attachment_file_type :doc
end
I wondering if rendering the index is causing the routing error as I got rid of temporarily by re-routing but the image was still null, documents/_index.html.erb
<div class="container">
<div class="row around-xs">
<center>
<% #documents.each do |document| %>
<li class="col-xs-3" id="item-grid">
<%= link_to image_tag(document.doc.url, class: 'media-object', size:"108x152"), document.doc.url, target: '_blank' %>
<% if #users %>
<% if current_user.is_admin? %>
<%= link_to 'Remove', document_path(document), class: 'btn btn-danger', method: :delete, data: {confirm: 'Are you sure?'} %>
<% end %>
<% end %>
</li>
<% end %>
</center>
</div>
</div>
home.html.erb
<section id="about" class="about-section">
<div class="container" id="services">
<div class="col-lg-8 col-md-offset-2" id="progpos"><h1>My Work</h1></div>
<%= render 'documents/index' %>
<br>
<%= render 'documents/new' %>
</div>
</section>
Please please help! thanks! documents/_new.html.erb
<% if #users %>
<% if current_user.is_admin? %>
<%= form_for #document, html: { multipart: true } do |f| %>
<% if #document.errors.any? %>
<div id="error_explanation">
<h2>
<%= "#{pluralize(#document.errors.count, "error")} prohibited this document from being saved:" %>
</h2>
<ul>
<% #document.errors.full_messages.each do |msg| %>
<li>
<%= msg %>
</li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group" style="width: 20%">
<%= f.file_field :doc, class: 'form-control', placeholder: "Document", multiple: true %>
</div>
<div class="form-group">
<%= f.submit 'Upload Document', class: 'btn btn-default' %>
</div>
<% end %>
<% end %>
<% end %>
Here's the whole of the controller and I've edited documents/_new.html.erb to how it looks:
class DocumentsController < ApplicationController
def index
#documents = Document.order('created_at')
end
def new
#document = Document.find(params[:id])
end
def create
#document = Document.new(doc_params)
if #document.save
**params[:document][:doc].each do |d| #iterate over multiple attached files
#document.create(doc: d)**
end
flash[:success] = "The document was added!"
redirect_to root_path
else
render '_new'
end
end
def destroy
#document = Document.find(params[:id])
if #document.destroy
flash[:notice] = "Successfully deleted photo!"
redirect_to root_path
else
flash[:alert] = "Error deleting photo!"
end
end
private
def doc_params
params.require(:document).permit(:id, **document: {doc: []}**)
end
end
I've added Pavans code to mine and i've also changed the params at the bottom which now gives me undefined method `create' for #. I think that's progress?
Unpermitted parameter: doc
You have multiple :true set for field doc, so doc should an array to accept the values. You should change the doc_params to below
def doc_params
params.require(:document).permit(:id, doc: [])
end
No handler found for
[#,
#original_filename="P1150645.jpg", #content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"document[doc][]\";
filename=\"P1150645.jpg\"\r\nContent-Type: image/jpeg\r\n">]
You should also set multipart: true to the form to handle file uploads
<%= form_for #document, html: { multipart: true } do |f| %>
ActionController::RoutingError (No route matches [GET]
"/docs/original/missing.png")
Paperclip will try to find missing.png when an object doesn't have an uploaded file and you have tell Paperclip where to find it!
class Document < ApplicationRecord
has_attached_file :doc, :styles => { :medium => "250x250>", :thumb => "150x150>" }, :default_url => "/system/:attachment/:style/missing.jpg"
do_not_validate_attachment_file_type :doc
end
Update:
Your create action should look like below
def create
#document = Document.new(doc_params)
if #document.save
params[:document][:doc].each do |d| #iterate over multiple attached files
#doumnet.create(doc: d)
end
flash[:success] = "The document was added!"
redirect_to root_path
else
render 'new'
end
end
I'm trying to make a search kick results page. However when i click search the console states i've got the correct id but the results page isnt opening.
I have this for my controller
def search
#events = Newevent.search params[:search]
render 'events/results'
end
I also have this as my search form
<div class="input-group input-group-lg">
<%= text_field_tag :search, params[:search], class: "form-control", autocomplete: "off" %>
<div class="input-group-btn">
<%= submit_tag "Search", class: "btn btn-primary" %>
</div>
</div>
<% end %>
And this is inside the results html.erb
<% #events.each do |event| %>
<h1>Test</h1>
<%= event.eventname %>
<% end %>
Heres what the console states when i start the search
Started GET "/search_events?utf8=%E2%9C%93&search=capital&commit=Search" for ::1 at 2015-11-21 15:18:33 +0000
Processing by NeweventsController#search as JS
Parameters: {"utf8"=>"✓", "search"=>"capital", "commit"=>"Search"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]]
Newevent Search (9.8ms) curl http://localhost:9200/newevents_development/_search?pretty -d '{"query":{"dis_max":{"queries":[{"match":{"_all":{"query":"capital","operator":"and","boost":10,"analyzer":"searchkick_search"}}},{"match":{"_all":{"query":"capital","operator":"and","boost":10,"analyzer":"searchkick_search2"}}},{"match":{"_all":{"query":"capital","operator":"and","boost":1,"analyzer":"searchkick_search","fuzziness":1,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}},{"match":{"_all":{"query":"capital","operator":"and","boost":1,"analyzer":"searchkick_search2","fuzziness":1,"prefix_length":0,"max_expansions":3,"fuzzy_transpositions":true}}}]}},"size":100000,"from":0,"fields":[]}'
Newevent Load (0.5ms) SELECT "newevents".* FROM "newevents" WHERE "newevents"."id" = 20
Rendered events/results.html.erb within layouts/application (1.6ms)
Rendered layouts/_navigation.html.erb (0.1ms)
Rendered layouts/_messages.html.erb (0.1ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 93ms (Views: 79.5ms | Searchkick: 9.8ms | ActiveRecord: 1.0ms)
Base on your server's log, I think you setup your search form as a remote form (you will see you have remote: true in your form_for tag)
Processing by NeweventsController#search as JS
Do you see text: as JS in the above line. That's because you submit a remote form. That means when you submit your form, the form will call ajax to server wait for server to return a js code to run on client side.
To solve your problem, just remove remote: true in your form_for tag, and everything will be ok ;)
So for some reason I'm getting a "invalid-request-cookie" when trying to submit a ReCaptcha. I'm using the ReCaptcha gem.
What am I doing wrong?
Also, I have my ReCaptcha public and private keys in my bash_profile so that shouldn't be an issue.
UsersStepsController.rb
class UserStepsController < ApplicationController
def show
end
def update
#user = current_user
captcha_message = "The data you entered for the CAPTCHA wasn't correct. Please try again"
if !verify_recaptcha(message: captcha_message)
render :add_recaptcha
else
redirect_to root_path and return
end
end
def add_recaptcha
#user = current_user
end
end
Routes.rb
patch '/user_steps', to: 'user_steps#update', as: 'update_user_steps'
resources :user_steps, except: [:update]
get '/add_recaptcha', to: 'user_steps#add_recaptcha'
user_steps/add_captcha.html.erb
<fieldset class="clearfix">
<div class="g-recaptcha" data-sitekey="6LeUQ_xxxx_etc"></div>
<div align="center"><%= recaptcha_tags :public_key => ENV['RECAPTCHA_PUBLIC_KEY'] %></div>
<%= form_for(#user, {url: update_user_steps_path(id: #user.to_param)}) do |f| %>
<br>
<%= f.submit "Done", class: "styling" %>
<% end %>
</div>
</fieldset>
Update Logs:
Started PATCH "/user_steps?id=35" for 127.0.0.1 at 2014-11-26 11:55:52 -0500
Started PATCH "/user_steps?id=35" for 127.0.0.1 at 2014-11-26 11:55:52 -0500
Processing by UserStepsController#update as HTML
Processing by UserStepsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"sEOPI8KVuXLPSLjXVajF8QcWeLcUpibgHq6hHqgtwGA=", "commit"=>"Done", "id"=>"35"}
Parameters: {"utf8"=>"✓", "authenticity_token"=>"sEOPI8KVuXLPSLjXVajF8QcWeLcUpibgHq6hHqgtwGA=", "commit"=>"Done", "id"=>"35"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 35 ORDER BY "users"."id" ASC LIMIT 1
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = 35 ORDER BY "users"."id" ASC LIMIT 1
Rendered layouts/_messages.html.erb (0.1ms)
Rendered layouts/_messages.html.erb (0.1ms)
Rendered layouts/headers/_header_sign_up_step2.html.erb (0.2ms)
Rendered layouts/headers/_header_sign_up_step2.html.erb (0.2ms)
Rendered user_steps/add_recaptcha.html.erb within layouts/application (28.2ms)
Rendered user_steps/add_recaptcha.html.erb within layouts/application (28.2ms)
Completed 200 OK in 919ms (Views: 800.4ms | ActiveRecord: 0.8ms)
Completed 200 OK in 919ms (Views: 800.4ms | ActiveRecord: 0.8ms)
Here is your answer :) You need to include that inside your form unless the value won't be saved!
<fieldset class="clearfix">
<%= form_for(#user, {url: update_user_steps_path(id: #user.to_param)}) do |f| %>
<div align="center"><%= recaptcha_tags :public_key => ENV['RECAPTCHA_PUBLIC_KEY'] %></div>
<br>
<%= f.submit "Done", class: "styling" %>
<% end %>
</div>
</fieldset>