Ruby On Rails - Controller doesn't open page while been called - html

calculate.html.erb of "calc" controller:
<h2>
<%= #count%>
</h2>
Form, which do the get request:
<%= form_with url: "/calc", method: :get do |form|%>
<%= form.label :count, "Введите количество чисел" %>
<%= form.number_field :count %>
<%= form.submit "Начать"%>
<% end %>
routes.rb:
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
# root "articles#index"
root 'pages#index'
get '/calc', to: 'calc#calculate'
end
In terminal, when I submit the form, I see this:
Started GET "/calc?count=5&commit=%D0%9D%D0%B0%D1%87%D0%B0%D1%82%D1%8C" for ::1 at 2023-01-23 16:51:04 +0300
Processing by CalcController#calculate as HTML
Parameters: {"count"=>"5", "commit"=>"Начать"}
Rendering text template
Rendered text template (Duration: 0.0ms | Allocations: 4)
Completed 200 OK in 2ms (Views: 0.5ms | Allocations: 206)
calc_controller.rb:
def calculate
render plain: params[:count].inspect
#count = params[:count]
end
P.s The URL doesn't change when I submit form

This line
render plain: params[:count].inspect
in your controller causes Rails to not render your view file but a plain text response.
Just remove that line and Rails should automatically render the view found in app/views/calc/calculate.html.erb

Related

Ruby on Rails:{Form does not load template to registration#create when button submit is hit}

#This is the RegistrationCOntroller to link the Model to the Form so that the data can be placed and when it is submitted a message of thanks will appear
`
class RegistrationController < ApplicationController
def new
#user = User.new
end
def create
render plain: "Thanks"
end
end
#The Form Page
<div class = "d-flex align-items-center justify-content-center">
<h1> Registration </h1>
</div>
<%= form_with module: #user, url: sign_up_path do |form| %>
<div class = "mb-3">
<%= form.label :email%>
<%= form.text_field :email, class:"form-control", placeholder:"Exaple#gmail.com"%>
</div>
<div class = "mb-3">
<%= form.label :password%>
<%= form.password_field :password, class:"form-control", placeholder:"Password"%>
</div>
<div class = "mb-3">
<%= form.label :password_confirmation%>
<%= form.password_field :password_confirmation, class:"form-control", placeholder:"Password"%>
</div>
<div class = "mb-3">
<%= form.submit "Register", class:"btn btn-primary"%>
</div>
<% end %>
#The routes for the project and the post method for the registration
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
# root "articles#index"
root to: "main#index"
get "about", to: "about#index"
get "sign_up", to: "registration#new"
post "sign_up", to: "registration#create"
end
`
#Note when the button is hit or the form is submitted no new page appears, and when i check the terminal for a response
Started POST "/sign_up" for 127.0.0.1 at 2022-11-13 08:49:52 -0400
Processing by RegistrationController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "email"=>"test#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "commit"=>"Register"}
Rendering text template
Rendered text template (Duration: 0.1ms | Allocations: 10)
Completed 200 OK in 5ms (Views: 3.4ms | ActiveRecord: 0.0ms | Allocations: 963)
#Also if i remove the PlainText thanks from the Registration Create section i end up with this instead
Started POST "/sign_up" for 127.0.0.1 at 2022-11-13 08:53:52 -0400
Processing by RegistrationController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "email"=>"test#gmail.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "commit"=>"Register"}
No template found for RegistrationController#create, rendering head :no_content
Completed 204 No Content in 2ms (ActiveRecord: 0.0ms | Allocations: 986)
#neither allows me to display my message on the post path "sign_up_path"
I tried renaming the routes path and trying various messages to display on the #create class object however I end up with the same result

Rails database error and incorrect message displayed - Online course on Upskill

After creating a form for the "contact us" page, I have validated the form to display "Message sent" and "Error occurred" when it is completed or left incomplete respectively.
Now when I fill the form properly and press submit, it shows "Error occurred" when it shouldn't.
This is what the terminal says when I press submit -
Started GET "/contacts/new" for 180.151.19.136 at 2020-09-08 20:25:29 +0000
Cannot render console from 180.151.19.136! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by ContactsController#new as HTML
Rendering contacts/new.html.erb within layouts/application
Rendered contacts/new.html.erb within layouts/application (2.1ms)
Completed 200 OK in 40ms (Views: 39.0ms)
Started POST "/contacts" for 180.151.19.136 at 2020-09-08 20:25:37 +0000
Cannot render console from 180.151.19.136! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by ContactsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"d6NOXW1mPMhhLExK/ltaYtCXWKykEcSXcGJv9O4eQ6NIDr9xmEDa+tqZmB0YdnThiydVWWoWGRGQ/8H9eR4ztw==", "contact"=>{"name"=>"okay okay"}, "commit"=>"Submit"}
(0.1ms) begin transaction
(0.0ms) rollback transaction
Redirected to https://dfb077768d054560bf89dc972cd52d7c.vfs.butt9.us-east-2.amazonaws.com/contacts/new
Completed 302 Found in 4ms
Started GET "/contacts/new" for 180.151.19.136 at 2020-09-08 20:25:38 +0000
Cannot render console from 180.151.19.136! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by ContactsController#new as HTML
Rendering contacts/new.html.erb within layouts/application
Rendered contacts/new.html.erb within layouts/application (3.0ms)
Completed 200 OK in 51ms (Views: 50.1ms)
This is my contact us page code, new.html.erb -
<div class="container">
<div class="row">
<h3 class="text-center">Contact Us</h3>
<div class="col-md-4 col-md-offset-4">
<%= flash[:notice] %>
<div class="well">
<%= form_for #contact do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.text_field :**name**, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :comments %>
<%= f.text_area :**name**, class: 'form-control' %>
</div>
<%= f.submit 'Submit', class: 'btn btn-default'%>
<% end %>
</div>
</div>
</div>
</div>
This is the contact.rb code -
class Contact < ActiveRecord::Base
validates :name, presence: true
validates :email, presence: true
validates :comments, presence: true
end
And this is the code on my controller file, contacts_controller.rb -
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
#contact = Contact.new(contact_params)
if #contact.save
redirect_to new_contact_path, notice: "Message sent."
else
redirect_to new_contact_path, notice: "Error occured."
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :comments)
end
end
This is the code I found on someone else's contacts_controller file following the same course -
class ContactsController < ApplicationController
# GET request to /contact-us
# Show new contact form
def new
#contact = Contact.new
end
# POST request /contacts
def create
# Mass assignment of form fields into contact object
#contact = Contact.new(contact_params)
# Save the Contact object to the database
if #contact.save
# Store form fields via parameters, into variables
name = params[:contact][:name]
email = params[:contact][:email]
body = params[:contact][:comments]
# Plug variables into Contact Mailer
# email method and send email
ContactMailer.contact_email(name, email, body).deliver
# Store success method in flash hash
# and redirect to the new action
flash[:success] = "Message sent."
redirect_to root_path
else
# If Contact object doesn't save,
# render to the new action
render 'new'
end
end
private
# To collect data from form, we need to use
# strong parameters and white list form fields
def contact_params
params.require(:contact).permit(:name, :email, :comments)
end
end
All my work can be found here. Please let me know if you require any other information.
Thank you for your time and help.
EDIT 1 - So the error was in new.html.erb. f.text_field/area had
'name' instead of the respective label name.
I fixed that and used the code I provided above and it is working now.
try this
def create
#contact = Contact.new
if #contact.update(contact_params)
redirect_to new_contact_path, notice: "Message sent."
else
redirect_to new_contact_path, notice: "Error occured."
end
end
So the error was in new.html.erb. f.text_field/area had 'name' instead of the respective label name.
I fixed that by replacing 'name' with 'email' and 'comments' respectively and used the code I provided above and it is working now.

Rails how to Render a form instead of redirect on submit?

I have a form that the results just show if render instead of redirect.
so the form must not be redirected. someone know if this is possible with rails?
the form is:
Pac: <%= #pac %>
Sedex: <%= #sedex %>
<%= form_tag calculate_ship_path, :method => "get" do %>
<%= text_field_tag :post_code%>
<% end %>
the order controller and action is:
def calculate_ship
frete = Correios::Frete::Calculador.new cep_origem: "#{#order.seller.post_code}",
:peso => "#{#order.product.weight}",
:comprimento => "#{#order.product.weight}",
:largura => "#{#order.product.weight}",
:altura => "#{#order.product.weight}",
cep_destino: params[:post_code]
servicos = frete.calcular :sedex, :pac
#pac = servicos[:pac].valor
#sedex = servicos[:sedex].valor
render '/path/to/rails/app//orders/:id/checkout'
end
and the routes is:
get '/path/to/rails/app//orders/:id/checkout', to: 'orders#checkout', as: :calculate_ship
Rails has a very handy way to handle this: remote forms. The caveat here is that if you're not using Unobtrusive JS (UJS) then this won't work and you'll have to wire it up the hard way.
In form tag notation it would look something like this, presuming you're using Rails 5:
<%= form_tag(calculate_ship_path, remote: true, method: "GET") do %>
<%# form stuff %>
<% end %>
You should be able to do this with most Rails versions, but it might look a little different. What this does, effectively, is submits your form via AJAX. You'll then be able to bind JS event listeners to ajax:success or ajax:error and handle the response you get from calculate_ship.
One thing to note is that when you're doing form submissions, the method is defaults to POST, and probably should be that, a PUT, or a PATCH.
Here's the related docs for rails: http://guides.rubyonrails.org/working_with_javascript_in_rails.html#form-tag

Show a different style sheet depending on page in rails 4

I am trying to render different CSS depending on the page. I did some research
How does one load a CSS framework in Rails 3.1?
https://github.com/rails/rails/issues/1981
and of course the rails guide on the asset pipeline.
What I want is for the index(home page) to render one css file(welcome.css.scss) and the others to render users.css.scss.
Right now when you navigate to the page it renders the welcome.css.scss and then when I hit sign in it is still rendering welcome.css.scss. But after refreshing the page it will then render the user.css.scss
I updated my assets.rb file:
Rails.application.config.assets.precompile += %w( welcome.css )
Rails.application.config.assets.precompile += %w( users.css )
Then I created a welcome.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Blocmarks</title>
<%= stylesheet_link_tag "welcome" %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
and a users.html.erb file
<!DOCTYPE html>
<html>
<head>
<title>Blocmarks</title>
<%= stylesheet_link_tag 'users' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
I removed the require from the application.css.scss. The only thing in the file at this time is #import 'bootstrap';
and of course I have a welcome and a user.css.scss.
Results from the console:
-Navigate to the home page
Started GET "/" for 127.0.0.1 at 2014-10-25 13:04:11 -0500
ActiveRecord::SchemaMigration Load (0.3ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by WelcomeController#index as HTML
Rendered welcome/index.html.erb within layouts/welcome (13.0ms)
Completed 200 OK in 471ms (Views: 446.7ms | ActiveRecord: 0.0ms)
Navigate to the users/sign-in
Started GET "/users/sign_up" for 127.0.0.1 at 2014-10-25 13:04:57 -0500
Processing by Devise::RegistrationsController#new as HTML
Rendered devise/shared/_links.erb (2.7ms)
Rendered devise/registrations/new.html.erb within layouts/devise (615.4ms)
Completed 200 OK in 896ms (Views: 890.9ms | ActiveRecord: 0.9ms)
Refresh the users/sign page:
Started GET "/users/sign_up" for 127.0.0.1 at 2014-10-25 13:06:02 -0500
Processing by Devise::RegistrationsController#new as HTML
Rendered devise/shared/_links.erb (0.8ms)
Rendered devise/registrations/new.html.erb within layouts/devise (7.4ms)
Completed 200 OK in 308ms (Views: 306.3ms | ActiveRecord: 0.0ms)
I also created a gist with the full console results to show what it is GETting first:
https://gist.github.com/tjperry07/b3093c0b7f16b5e000b0
This is happening because of rails turbolinks. It makes following links in your web application faster. Instead of letting the browser recompile the JavaScript and CSS between each page change, it keeps the current page instance alive and replaces only the body and the title in the head.
If you look at guides or turbolinks docs. It's clearly stated that
If using the turbolinks gem, which is included by default in Rails 4, then include the 'data-turbolinks-track' option which causes turbolinks to check if an asset has been updated and if so loads it into the page
FIX:
Replace your stylesheet tags with these:
<%= stylesheet_link_tag "welcome", media: "all", "data-turbolinks-track" => true %>
<%= stylesheet_link_tag "users", media: "all", "data-turbolinks-track" => true %>

Ruby on Rails not detecting comment field

I'm trying to build a very basic Rails app for posting images with a comment. The comment is a required field and the image upload should only go ahead if the comments section has a value, displaying an error message otherwise.
The problem I am having is that even when the comments section is filled in it still displays an error saying that it cannot be blank.
I have tried adding attr_accessor's with the html field names and database values but it makes no difference.
Posts model
class Post < ActiveRecord::Base
has_attached_file :picture, styles: { medium: "300x300>", thumb: "100x100>" }
attr_accessor :picture_file_name
attr_accessor :post_description
validates :description, presence: true
end
Posts controller
class PostsController < ApplicationController
def index
#posts = Post.all
end
def new
#post = Post.new
end
def create
#post = Post.new params[:post].permit(:description, :picture)
if #post.save
redirect_to '/posts'
else
render 'new'
end
end
end
new.html.erb
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form_for #post, :html => { :multipart => true } do |f| %>
<%= f.label :description %>
<%= f.text_area :description %>
<%= f.label :picture %>
<%= f.file_field :picture %>
<%= f.submit %>
<% end %>
Server readout
=> Booting WEBrick
=> Rails 4.0.4 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2014-04-20 17:59:07] INFO WEBrick 1.3.1
[2014-04-20 17:59:07] INFO ruby 2.1.0 (2013-12-25) [x86_64-darwin12.0]
[2014-04-20 17:59:07] INFO WEBrick::HTTPServer#start: pid=98772 port=3000
Started POST "/posts" for 127.0.0.1 at 2014-04-20 17:59:21 +0100
ActiveRecord::SchemaMigration Load (0.2ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by PostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nVrCEAdT+epbltQWR74jtv1weGaq6H7YbWQKFfJNDTw=", "post"=>{"description"=>"test comment", "picture"=>#<ActionDispatch::Http::UploadedFile:0x0000010242f740 #tempfile=#<Tempfile:/var/folders/lm/vrw53rx91831vrh4228m0mfw0000gn/T/RackMultipart20140420-98772-1c9msrz>, #original_filename="dory_2.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\"dory_2.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create Post"}
WARNING: Can't mass-assign protected attributes for Post: description, picture
app/controllers/posts_controller.rb:12:in `create'
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendered posts/new.html.erb within layouts/application (13.1ms)
Completed 200 OK in 105ms (Views: 65.6ms | ActiveRecord: 0.4ms)
Your params & form look okay
But I would change your strong params to be more conventional:
def create
#post = Post.new(post_params)
#post.save
end
private
def post_params
params.require(:post).permit(:description, :picture)
end
I found the problem.
The issue was that I had originally installed the latest version of Paperclip and then downgraded.
I had added the following gem while I was searching for a solution
gem 'protected_attributes'
This was causing all required fields not to register they were being filled in, such as in user sign up fields etc.
Once that gem was removed it worked just fine.