How do you fix a form page that is giving you a 422 error? - html

I have been using Ruby on Rails for an app and have a long line of forms I am trying to use in the process. They have all been working perfectly but when I select submit after filling out all the information, the screen doesn't change on in 'inspect' it says the form is not assigned to any user.
I checked each form controller and I had something like this:
def create
#crew_applicant_form = CrewApplicantForm.new(crew_applicant_form_params)
#crew_applicant_form.user = current_user
respond_to do |format|
if #crew_applicant_form.save
format.html { redirect_to crew_applicant_form_url(#crew_applicant_form), notice: "Crew applicant form was successfully created." }
format.json { render :show, status: :created, location: #crew_applicant_form }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #crew_applicant_form.errors, status: :unprocessable_entity }
end
end
end
Any suggestions on what I'm doing wrong here? I can send over the code html and model if need be

Related

How to place a form to create a new entry on the main page. RoR

I install Ubuntu, RoR and all RoR components. Then I update question.
I need to get the form as in this screenshot. I need this part. So that it appears after clicking the Add button. I understand the logic of adding a form after clicking a button, but I can’t understand how the code of the form itself should look. Even a form with only text_field launches a site with an error 500. I may not know a lot, I'm just learning RoR.
index.html.erb
<style type="text/css">
p{
font-family: Times New Roman
}
</style>
<p>
<strong><h1><%= #title %></h1>
<br><br><br>
<% #projects.each do |project| %>
<h2 style="text-transform: uppercase"><%= project.title %></h2>
<ul>
<% #todos.each do |todo| %>
<% if todo.project_id == project.id %>
<li><%= todo.text %></li>
<% end %>
<% end %>
</ul>
<% end %>
<h2>Новая задача</h2>
<%= form_with(model: #todo, local: true) do |todo| %>
<%= todo.text_field :text %>
<%= todo.select (:project_id, option_for_select(project_array)) %>
<%= todo.submit "Отмена"%>
<%= todo.submit "ОК" %>
<% end %>
</strong>
</p>
projects_controller.rb
class ProjectsController < ApplicationController
before_action :set_project, only: [:show, :edit, :update, :destroy]
# GET /projects
# GET /projects.json
def index
#projects = Project.all
end
# GET /projects/1
# GET /projects/1.json
def show
end
# GET /projects/new
def new
#project = Project.new
end
# GET /projects/1/edit
def edit
end
# POST /projects
# POST /projects.json
def create
#project = Project.new(project_params)
respond_to do |format|
if #project.save
format.html { redirect_to #project, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: #project }
else
format.html { render :new }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /projects/1
# PATCH/PUT /projects/1.json
def update
respond_to do |format|
if #project.update(project_params)
format.html { redirect_to #project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: #project }
else
format.html { render :edit }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
# DELETE /projects/1
# DELETE /projects/1.json
def destroy
#project.destroy
respond_to do |format|
format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_project
#project = Project.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def project_params
params.require(:project).permit(:title)
end
end
todos_controller.rb
class TodosController < ApplicationController
before_action :set_todo, only: [:show, :edit, :update, :destroy]
# GET /todos
# GET /todos.json
def index
#todos = Todo.all
end
# GET /todos/1
# GET /todos/1.json
def show
end
# GET /todos/new
def new
#todo = Todo.new
end
# GET /todos/1/edit
def edit
end
# POST /todos
# POST /todos.json
def create
#todo = Todo.new(todo_params)
respond_to do |format|
if #todo.save
format.html { redirect_to #todo, notice: 'Todo was successfully created.' }
format.json { render :show, status: :created, location: #todo }
else
format.html { render :new }
format.json { render json: #todo.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /todos/1
# PATCH/PUT /todos/1.json
def update
respond_to do |format|
if #todo.update(todo_params)
format.html { redirect_to #todo, notice: 'Todo was successfully updated.' }
format.json { render :show, status: :ok, location: #todo }
else
format.html { render :edit }
format.json { render json: #todo.errors, status: :unprocessable_entity }
end
end
end
# DELETE /todos/1
# DELETE /todos/1.json
def destroy
#todo.destroy
respond_to do |format|
format.html { redirect_to todos_url, notice: 'Todo was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_todo
#todo = Todo.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def todo_params
params.require(:todo).permit(:text, :isCompleted, :project_id)
end
end
todoshnik_controller.rb
class TodoshnikController < ApplicationController
def index
#title = 'Задачи'
#projects = Project.all
#todos = Todo.all
#todo = Todo.new
#project_array = #projects.map { |project| [project.title, project.id] }
end
def create
end
def update
end
end
routes.rb
Rails.application.routes.draw do
root 'todoshnik#index'
resources :todos
resources :projects
end
Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.5'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.0'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Active Storage variant
# gem 'image_processing', '~> 1.2'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of web drivers to run system tests with browsers
gem 'webdrivers'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
Add a #todo instance variable in the index action
def index
#title = 'Задачи'
#projects = Project.all
#todos = Todo.all
#todo = Todo.new
#project_array = #projects.map { |project| [project.title, project.id] } #minimize the use of logic in your views.
end
Add the form in your view.
<%= form_for #todo do |todo| %>
<%= todo.text_field :text %>
<%= todo.select :project_id, options_for_select(#project_array) %>
<%= todo.submit "Отмена" %>
<%= todo.submit "ОК" %>
<% end %>
If you have a TodoController with create and update action
<%= form_with(model: #todo, local: true) do |todo| %>
<%= todo.text_field :text %>
<%= todo.select :project_id, options_for_select(#project_array) %>
<%= todo.submit "ОК" %>
<% end %>
This will always point to the create action of the TodoController
The problem is #todo is not referenced in your index_controller.rb, so your index_controller.rb #index action must be:
def index
#title = 'Задачи'
#projects = Project.all
#todos = Todo.all
#todo = Todo.new
end
Then in your index.html.erb
<%= form_for #todo do |todo| %>
<%= todo.text_field :text %>
<%= project_array = #projects.map { |project| [project.title, project.id] } %>
<%= todo.select (:project_id, option_for_select(project_array)) %>
<%= todo.submit "Отмена" %>
<%= todo.submit "ОК" %>
<% end %>
try to install simple_form_for gem. It will allow you makes form without any troubles.

undefined method unpack for nil:NilClass when rendering JSON

I'm working on a Rails 5 API application and Im having trouble when trying to render json. Take that simple controller:
module Api
module V1
class UsersController < ApplicationController
def sign_up
#user = User.new user_params
if #user.save
render json: {status: :ok, user: #user.to_json }
else
render json: { status: :error, errors: #user.errors }, status: :unprocessable_entity
end
end
end
end
end
When I test this request with a simple spec:
RSpec.describe Api::V1::UsersController, type: :controller do
context 'As an unregistered user' do
context 'signing up with valid params' do
let(:valid_params) do
{ name: 'Test User', email: 'test#test.com', password: '123456789', password_confirmation: '123456789' }
end
it 'returns a 200 status' do
post :sign_up, params: { user: valid_params }
expect(response.status).to eq 200
end
end
end
end
I get an error thrown at me:
Failures:
1) Api::V1::UsersController As an unregistered user signing up with valid status returns a 200 status
Failure/Error: render json: {status: :ok, user: #user.to_json }
NoMethodError:
undefined method `unpack' for nil:NilClass
# ./app/controllers/api/v1/users_controller.rb:10:in `sign_up'
# ./spec/controllers/api/v1/users_controller_spec.rb:15:in `block (4 levels) in <top (required)>'
I'm not using any gems that alter rendering yet so I'm really lost of what might be the problem. Thanks in advance.

Dynamic aspects of Rails 4 app not working in production

I just deployed my first rails 4 app to a VPS and now I cannot write to the production database. Everything deployed fine (migrations etc) and I can log on the mysql database with sequel pro and see it is all there however when I try create a user using the app's new user form instead of notifying 'Thank you for registering' (as it does in development) it asks me to login to proceed. No record is created in the database.
I can see in the log that it is binding show rather than the users id to the :id parameter and therefore redirecting to login rather than creating a session. Why would this be?
This is the app log
I, [2014-08-09T00:33:45.753714 #31030] INFO -- : Started GET "/login" for xx.xxx.xxx.xx at 2014-08-09 00:33:45 +0200
I, [2014-08-09T00:33:45.755372 #31030] INFO -- : Processing by SessionsController#new as HTML
I, [2014-08-09T00:33:45.757942 #31030] INFO -- : Rendered sessions/new.html.erb within layouts/application (1.1ms)
I, [2014-08-09T00:33:45.758940 #31030] INFO -- : Completed 200 OK in 3ms (Views: 2.5ms | ActiveRecord: 0.0ms)
I, [2014-08-09T00:33:52.048559 #31030] INFO -- : Started POST "/sessions" for xx.xxx.xxx.xx at 2014-08-09 00:33:52 +0200
I, [2014-08-09T00:33:52.050765 #31030] INFO -- : Processing by SessionsController#create as HTML
I, [2014-08-09T00:33:52.050912 #31030] INFO -- : Parameters: {"utf8"=>"?^?^?", "authenticity_token"=>"xxxxxxxxxxxxxxxx", "email"=>"xxxx#gmail.com", "password"=>"[FILTERED]", "commit"=>"Log In"}
I, [2014-08-09T00:33:52.056027 #31030] INFO -- : Rendered sessions/new.html.erb within layouts/application (1.4ms)
I, [2014-08-09T00:33:52.057333 #31030] INFO -- : Completed 200 OK in 6ms (Views: 3.1ms | ActiveRecord: 0.7ms)
I, [2014-08-09T00:34:16.625949 #31030] INFO -- : Started GET "/users/show" for 92.225.136.50 at 2014-08-09 00:34:16 +0200
I, [2014-08-09T00:34:16.628217 #31030] INFO -- : Processing by UsersController#show as HTML
I, [2014-08-09T00:34:16.628359 #31030] INFO -- : Parameters: {"id"=>"show"}
I, [2014-08-09T00:34:16.630009 #31030] INFO -- : Redirected to http://xx.xxx.xxx.xx/
I, [2014-08-09T00:34:16.630207 #31030] INFO -- : Filter chain halted as :authorize rendered or redirected
I, [2014-08-09T00:34:16.630443 #31030] INFO -- : Completed 302 Found in 2ms (ActiveRecord: 0.0ms)
Edit 1: Here is my session controller:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to users_path, notice: "Logged In!"
else
flash.now[:error] = "Email or password is invalid. Please try again."
render "new"
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Logged Out!"
end
end
And here is my users controller:
class UsersController < ApplicationController
before_action :authorize, except: [:new]
def new
#user = User.new
end
def edit
#user = User.find(params[:id])
end
def show
#user = User.find(params[:id])
#microposts = #user.microposts.paginate(page: params[:page])
end
def update
respond_to do |format|
#user = User.find(params[:id])
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def destroy
#user = User.find(params[:id])
if #user.present?
#user.destroy
end
redirect_to users_path, notice: "User successfully deleted."
end
def create
#user = User.new(params[:user].permit(:name, :surname, :title, :telefon, :email, :password, :password_confirmation, :salt, :encrypted_password))
if #user.save
session[:user_id] = #user.id
redirect_to root_url, notice: "Vielen Dank für Ihre Anmeldung"
else
render "new"
end
end
def index
#users = User.all
end
private
def user_params
params.require(:user).permit(:name, :surname, :title, :telefon, :email, :password, :password_confirmation, :salt, :encrypted_password)
end
end

why my mysql DB can read without update or insert data in Rails 4?

Guy I got something strange in my project
Now I got old ruby on rails project to develop some notes in it after I activate the commands
bundle
bundle exec rake db:create
bundle exec rake db:migrate
rails s
First the application asked me to install mysql2 0.3.14 and after installed it I got the error
log writing faild. invalid byte sequence in US-ASCII
and I solved it by added the #encoding: utf-8 in every first line in the project models
and finally now I can open my project well but
I found when I read data from my DB it work well when tried to insert or update any data from my MYSQL DB nothing happen with me !!!!! I thought that my DB user only take permissions to read only from the DB but after checked the user permissions I found it takes all the permissions
So can any one explain to me why I go this issue ????
This is a simple code to insert into my MYSQL DB
the View code
<%= form_for(#category) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :icon %><br>
<%= f.file_field :icon %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
controller code
def create
#Just test to insert fixed data to my DB but also not insert any thing
#category =Category.new(:title => 'eeeee', :icon_file_name => 'xxx', :slug => 'sug')
##category =Category.new(:title => params[:title], :icon_file_name => params[:icon], :slug => params[:slug])
##category = Category.new(category_params)
respond_to do |format|
if #category.save
format.html { redirect_to #category, notice: 'Category was successfully created.' }
format.json { render action: 'show', status: :created, location: #category }
else
format.html { render action: 'new' }
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end
Note: I'm using Windows 7
Seems like you didn't sanitize your params. In Rails 4 strong parameters have been introduced in order to increase security of untrusted sources posting data to your database.
So in your controller you have to add a private method (if you generated it with scaffolding it should be already present) to say which parameters to accept.
in your case should be something like
def category_params
params.require(:category).permit(:title, :icon_file_name, :slug, :whatever_other_param_you_need)
end
Read more here http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

Connecting to a separate mysql database in Rails

I am trying to connect to a separate mysql database than what my rails app is on. I am trying to connect to a database of guitar tabs so that users can search for specific songs.
I have my database.yml configured to:
tabs:
adapter: mysql2
encoding: utf8
database: (dbname)
username: (username)
password: (pass)
host: hostname.rds.amazonaws.com
port: 3306
So far I have tab.rb as my model:
class Tab < ActiveRecord::Base
self.abstract_class = true
establish_connection ('tabs')
end
finally, my controller
class TabController < ApplicationController
def listTabs
#tabs = Tabs.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #tabs }
end
end
def showTabs
#tabs = Tabs.find_by_sql "SELECT * FROM gp"
respond_to do |format|
format.html # index.html.erb
format.json { render json: #statuses }
end
end
end
I'm new to rails and I really want to get this to work. If you are able to help me just run the query "SELECT * From gp" and display it in my view, I will love you forever.
Thanks for your help!
in your model the name is Tab and you use in controller Tabs i.e is wrong, please use Tab.all or Tab.find_by_sql