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

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.

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

Getting error (undefined method) for form_with

I have _form.html.erb. and on the first line of code, it is throwing this error:
undefined method `assessments_path' for #ActionView::Base:0x00000000229750
Did you mean? asset_path
couple of points:
in routes 'poweruser' is a namespace
in models assessment.rb is
not folder poweruser (as I plan to use it for other pages that anyone can access not just powerusers).
Any ideas what I am missing?
Here is the code:
<%= form_with(model: [#assessment], local: true) do |form| %>
<%= render "shared/error_messages", resource: form.object %>
<div class="form-group">
<%= form.label :name %>
<%= form.text_field :name, class: "form-control" %>
</div>
<% end %>
Here is the controller
module Powerusers
class AssessmentsController < ApplicationController
before_action :authenticate_user!
# before_action :set_assessment
# before_action :set_assessment, only: [:set_assessment, :show, :edit, :update, :destroy]
# Overwrite any of the RESTful controller actions to implement custom behavior
# For example, you may want to send an email after a foo is updated.
#
# def update
# super
# send_foo_updated_email(requested_resource)
# end
def index
#pagy, #assessments = pagy(Assessment.sort_by_params(params[:sort], sort_direction))
# We explicitly load the records to avoid triggering multiple DB calls in the views when checking if records exist and iterating over them.
# Calling #assessments.any? in the view will use the loaded records to check existence instead of making an extra DB call.
#assessments.load
end
# GET /assessments/new
def new
#assessment = Assessment.new
#assessment.assessment_sections.new
end
here is the assessment.rb (not it is not in a sub-folder poweruser)
class Assessment < ApplicationRecord
belongs_to :company
has_many :assessment_sections, inverse_of: :assessment
has_many :questions, through: :assessment_sections
accepts_nested_attributes_for :assessment_sections, reject_if: :all_blank,
allow_destroy: true
accepts_nested_attributes_for :questions, reject_if: :all_blank,
allow_destroy: true
end
Here is the routes
# PowerUser
authenticated :user, lambda { |u| u.admin? } do
namespace :powerusers do
resources :assessments do
resources :assessment_sections do
resources :questions
end
end
end
end
As you have namespace in routes, you need to specify that with form_with
<%= form_with(model: [:powerusers, #assessment], local: true) do |form| %>

Rails undefined method `email' for nil:NilClass

I get the following error in Rails application. Can you help me?
I get an error when I connect two tables.
The user wants to use a table. I'm trying to manage the manager ID and user ID fields from a single table.
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]
Rails 5.2.2
Database Design
Error Message
Database design and tables
schema.rb:
ActiveRecord::Schema.define(version: 2019_02_24_160401) do
create_table "projects", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
t.string "name"
t.text "description"
t.string "company"
t.bigint "manager_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["manager_id"], name: "index_projects_on_manager_id"
end
create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "username", default: "", null: false
t.string "fullname", default: ""
t.bigint "manager"
t.string "company", default: ""
t.string "department", default: ""
t.boolean "isadmin", default: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "projects", "users", column: "manager_id"
end
projects_controller.rb
class ProjectsController < ApplicationController
before_action :set_project, only: [:show, :edit, :update, :destroy]
before_action :find_users, only: [:index, :show, :new, :edit]
# 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
def find_users
#users = User.all.order('created_at desc')
end
# Never trust parameters from the scary internet, only allow the white list through.
def project_params
params.require(:project).permit(:name, :description, :user_id)
end
end
Model files in model folder
project.rb and user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
has_many :projects
end
class Project < ApplicationRecord
belongs_to :user
end
calling my code email column
index.html.erb
<p id="notice"><%= notice %></p>
<h1>Projects</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Company</th>
<th>Manager</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #projects.each do |project| %>
<tr>
<td><%= project.name %></td>
<td><%= project.description %></td>
<td><%= project.company %></td>
<td><%= project.user.email %></td>
<td><%= link_to 'Show', project %></td>
<td><%= link_to 'Edit', edit_project_path(project) %></td>
<td><%= link_to 'Destroy', project, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Project', new_project_path %>
Your Project has a manager_id, but no table called managers, instead it's users. So in your relationship between projects and users, it needs to use the correct key.
class User < ApplicationRecord
has_many :projects, foreign_key: :manager_id
end
class Project < ApplicationRecord
belongs_to :user, foreign_key: :manager_id
end
It seems the data is not well drafted in the schema. Is User the same thing as Manager? If it is not, you should have a user_id reference in the Projects table else, you'll have to add proper associations tying manager_id to Users then you can have project.manager.email
If user is optional for Project just call project.user&.email

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