Dynamic aspects of Rails 4 app not working in production - mysql

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

Related

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

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

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.

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

cURL post to server resulting in a UnknownFormat error

I am very new at rails and having a hard time doing a cURL post to my server. Any help would be apreciated.
I am posting JSON data to my server.
this is my curl post curl -X POST -H "Content-Type: application/json" -d '[{"photo":[{ "location": "location", "userID": "userid" },{ "location": "location", "userID": "userid" },{"location": "location", "userID": "userid"}]}]' http://localhost:3000/photo/create
this is my controller:
class SendphotoController < ApplicationController
def create
#photo = Photo.new(:photo => params[:location], :photo => params[:userID])
respond_to do |format|
if #photo.save
puts "Done"
else
puts "NOPE"
end
end
end
I get the error of ActionController::UnknownFormat (ActionController::UnknownFormat):
This is the full log:
Started POST "/photo/create" for 127.0.0.1 at 2013-09-08 22:03:56 -0400
Processing by SendphotoController#create as */*
Parameters: {"_json"=>[{"photo"=>[{"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}]}], "sendphoto"=>{"_json"=>[{"photo"=>[{"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}, {"location"=>"location", "userID"=>"userid"}]}]}}
WARNING: Can't mass-assign protected attributes for Photo: photo
app/controllers/sendphoto_controller.rb:4:in `create'
(0.0ms) begin transaction
SQL (0.3ms) INSERT INTO "photos" ("created_at", "updated_at") VALUES (?, ?) [["created_at", Mon, 09 Sep 2013 02:03:56 UTC +00:00], ["updated_at", Mon, 09 Sep 2013 02:03:56 UTC +00:00]]
(215.8ms) commit transaction
Done
Completed 406 Not Acceptable in 235ms
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/sendphoto_controller.rb:5:in `create'
You're using a respond_to block, but not any formats. Your block should look something like this:
respond_to do |format|
format.html {
# respond to a web form with HTML
}
format.json {
# respond to API request
}
end
If you just want a generic response for all formats, you can drop the respond_to bit altogether. But puts isn't going to work in a Controller context (or pretty much anywhere in Rails for that matter); you have to render something.
That might look something like this
def create
if Photo.create # ...
render text: "done"
else
render text: "nope"
end
end

Unable to pass params data to create a user

I have a rails app that accepts json request to create a user. A sign_up basically which is a GET. I can't create a user when i pass in this url http://localhost:3000/sign_up.json?username=chalam&email=holy#yahoo.com&name=chalami&password=chalami
I know I am passing the password in the open but that is not my concern here. i checked the logs and this is what i see
Started GET "/sign_up.json?username=chalam&email=holy#yahoo.com&name=chalami&password=[FILTERED]" for 127.0.0.1 at 2013-05-28 10:37:37 +0700
Processing by UsersController#create as JSON
Parameters: {"username"=>"chalam", "email"=>"holy#yahoo.com", "name"=>"chalami", "password"=>"[FILTERED]"}
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1
User Exists (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
(0.0ms) rollback transaction
(0.0ms) begin transaction
CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1
CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
(0.0ms) rollback transaction
Completed 200 OK in 6ms (Views: 0.1ms | ActiveRecord: 0.3ms)
As you can see although the parameter Parameters: {"username"=>"chalam", "email"=>"holy#yahoo.com", "name"=>"chalami", "password"=>"[FILTERED]"} clearly show that parameters are being passed, they are not being entered into the database CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1
CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
Main problem is data from the params is not being "used" to create a User
One thing to note is I can create a user through the console in terminal. I will try to include all relevant information
rails version: 3.2.13 and
I am using thin instead of WEBBRICK
My user.rb
class User < ActiveRecord::Base
attr_accessible :email, :name, :username
attr_accessor :password
before_save :encrypt_password
validates_uniqueness_of :username, :email
validates_presence_of :password, :on => :create
validates_presence_of :email, :username
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
def self.authenticate(username, password)
user = find_by_username(username)
if(user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt))
user
else
nil
end
end
end
My Controller
class UsersController < ApplicationController
respond_to :json
def new
#user = User.new
end
def create
#user = User.new(params[:user])
#user.save
if #user.save
respond_to do |format|
format.json { render :json => {:status => "200", :message => "Signed up successfully"}}
end
else
respond_to do |format|
puts #user.errors.inspect
format.json { render :json => {:status => "400", :message => "Failed"}}
end
end
end
def index
#user = User.all
render :json =>#user
end
end
Okay, so I have come up with a solution and I thought I should post it, it might help people
Problem: I could not create a user using a Json response although I could do it through rails console
Mistakes:
I created a GET route to create a User which compromises security
I added the password field to attr_accessor and not to attr_accessible
Solutions:
changed the action from GET to POST(in the routes.rb). To create a user(for a POST) I used curl. In my case my curl statement was
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d ' {"user":{"name":"name","username":"username","email":"email#email.com","password":"app123"}}' http://localhost:3000/sign_up. Here is a useful post about curl
2.In my user model I included attr_accessor :password as well as attr_accessible :password