Code Monkey home page Code Monkey logo

rentalcars's Introduction

Titulo do Projeto

Lista de Conteúdos

🔸 Descrição do Projeto

🔸 Deploy

🔸 Pré-requisitos

🔸 Configurações

🔸 Rodando a aplicação

🔸 Rodando os testes

🔸 Database

🔸 Rotas

🔸 Resolvendo Problemas

🔸 Licença

Status do Projeto

Em manutenção ⚠️

README em Ingles

README

Descrição do Projeto 🏁

O projeto é uma aplicação backend com Ruby on Rails para um sistema interno de aluguel de carros. O administrador pode criar uma conta e agendar uma locação, escolhendo o modelo do carro, categoria, data de agendamento, etc.

Deploy

Pré-requisitos 📦

Algumas instalações serão necessárias antes de iniciar o projeto.

⚠️ Ruby versão >=3.1.2

⚠️ Ruby on Rails versão >=7.0.2

⚠️ Node versão >=12.16.2

⚠️ Gem versão >=3.1.2

⚠️ Bundle versão >=2.1.2

⚠️ Yarn versão >=1.22.4

⚠️ Docker

Verifique se as libs foram instaldas e estão na versão correta executando no terminal:

$ <nome da lib em minusculo> -v 

Configurações ▶️

  1. Clone o projeto
$ git clone https://github.com/reginadiana/rentalcars
  1. Entre no diretório
$ cd rentalcars
  1. Agora vamos rodar a aplicação com Docker:

docker-compose build

docker-compose run --service-ports web bash

Um novo terminal irá abrir, então, execute:

$ rails s -b 0.0.0.0

Depois, acesse http://localhost:3000 para ver a aplicação

Rodando os testes 📝

$ cd rentalcars
$ rspec or bundle exec rspec

Database 💾

As tabelas do banco de dados podem ser vistas no arquivo schema

Os dados default foram criados em seeds

Rotas

Para ver as rotas disponíveis na aplicação, execute:

$ rails routes -g <name of controller>

Resolvendo Problemas ⬆️

Em issues foram abertos alguns problemas gerados durante o desenvolvimento desse projeto e como foram resolvidos.

Licença 🔱

The MIT License (MIT)

Copyright ©️ 2022 Rental Cars

rentalcars's People

Contributors

dependabot[bot] avatar reginadiana avatar

Watchers

 avatar

rentalcars's Issues

Docker: /bin/sh: 1: npm: not found

Adicione no seu Dockerfile os seguintes comandos:

RUN curl -sL https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

Your webpack configuration is not creating a manifest.

Webpacker can't find application.js in /home/diana/plataforma-headhunters-treina-dev/public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
Your manifest contains:

Como resolver:

yarn add @rails/webpacker
bundle update webpacker

Outra solução é:

Mudei a versão do node para 16.3.1 por ser uma versão estável (LTS). A versão 17 pode ser até a mais atualizada, mas não é tão segura como a LST

# Dockerfile
ENV NODE_VERSION 16

Depois, criei uma rota home no Rails, porque se não ele irá sempre para o Yah! Rails 😅

# config/routes.rb
Rails.application.routes.draw do
  root to: 'home#index'
end

Depois, criei uma view em view/home/index.erb mas não coloquei nada nele.

Em application.html.erb coloquei <%= javascript_pack_tag 'hello_react' %> dentro da tag <head> assim como é instruído em hello_react.jsx

No terminal, rodei o comando rails assets:precompile, bin/setup e por fim rails s -b 0.0.0.0

Referencias

📚 Webpacker can't find application in ... manifest.json (at runtime)
📚 How to use React with Ruby on Rails 6
📚 Node Version

Object must be a Date, DateTime or Time object. nil given.

Criei as datas como tipo date no banco e usei o I18n pra formata-las:

Tentativa 1:

<dt>Data de término:</dt>
<dd><%= localize(rental.end_date, format: :long) %></dd>

Tentativa 2:

<dt>Data de inicio:</dt>
<dd><%= l(rental.start_date, format: :long) %></dd>

Tentativa 3:

<dt>Data de inicio:</dt>
<dd><%= l rental.start_date %></dd>

Apenas usando dessas 2 formas obtive sucesso:

<dt>Data de inicio:</dt>
<dd><%= rental.start_date && localize(rental.start_date) %></dd>

DD/MM/YYYY

<dt>Data de inicio:</dt>
<dd><%= rental.start_date && localize(rental.start_date, format: :long) %></dd>

Data por exenso

uninitialized constant RentalsController::Rental

Failure/Error: @rental = Rental.new
     
     NameError:
       uninitialized constant RentalsController::Rental
       Did you mean?  RentalCars

Significa que o model nao foi criado, crie com:

rails g model rental <atributos>

Erro ao executar bin/setup

Erro:

The Gemfile's dependencies are satisfied

== Preparing database ==
rails aborted!
LoadError: Could not load the 'listen' gem. Add `gem 'listen'` to the development group of your Gemfile
/home/diana/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.6/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in 'require'

Como resolver:

  • Abra a Gemfile e acrescente gem 'listen' ao grupo group :development, :test do

SQLite3::BusyException: database is locked

Excute no terminal:

rails db:drop db:create db:migrate

ou

bundle exec rails db:drop db:create db:migrate

Parar recuperar os dados do arquivo seed.rb, digite:

rails db:seed

bin/setup: line 4: puts: command not found

Arquivo bin/setup:

# frozen_string_lateral: true
#!/usr/bin/env ruby

puts '== Installing dependencies =='

Solução:

Apague a linha # frozen_string_lateral: true ou inverta a ordem com a linha de baixo

Erro bcrypt em ao instalar device

Apos adicionar gem 'devise' e rodar o bundle, tive o erro:

Fetching bcrypt 3.1.13
Installing bcrypt 3.1.13 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory:
/home/diana/.rvm/gems/ruby-2.6.3/gems/bcrypt-3.1.13/ext/mri
/usr/share/rvm/rubies/ruby-2.6.3/bin/ruby -I
/usr/share/rvm/rubies/ruby-2.6.3/lib/ruby/site_ruby/2.6.0 -r
./siteconf20200502-3857-159zmaw.rb extconf.rb
creating Makefile

current directory:
/home/diana/.rvm/gems/ruby-2.6.3/gems/bcrypt-3.1.13/ext/mri
make "DESTDIR=" clean

current directory:
/home/diana/.rvm/gems/ruby-2.6.3/gems/bcrypt-3.1.13/ext/mri
make "DESTDIR="
compiling bcrypt_ext.c
compiling crypt_blowfish.c
gcc -D__SKIP_GNU -D_FILE_OFFSET_BITS=64 -c -o x86.o x86.S
x86.S: Assembler messages:
x86.S:202: Error: junk at end of line, first unrecognized character is
`,'
: recipe for target 'x86.o' failed
make: *** [x86.o] Error 1

make failed, exit code 2

Gem files will remain installed in
/home/diana/.rvm/gems/ruby-2.6.3/gems/bcrypt-3.1.13 for inspection.
Results logged to
/home/diana/.rvm/gems/ruby-2.6.3/extensions/armv7l-linux-eabihf/2.6.0/bcrypt-3.1.13/gem_make.out

An error occurred while installing bcrypt (3.1.13), and Bundler
cannot continue.
Make sure that gem install bcrypt -v '3.1.13' --source 'https://rubygems.org/' succeeds before bundling.

In Gemfile:
devise was resolved to 4.7.1, which depends on
bcrypt

Para resolver, abra o aquivo Gemfile e adicione gem 'bcrypt', '3.1.12' antes de device e rode bundle novamente

Erro ao instalar Gem

Quando executei o comando bundle install e bundle update recebi este erro;

ERROR:  Could not find a valid gem 'bundler' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - timed out (https://rubygems.org/specs.4.8.gz)

Como root, quase a mesma coisa:

/usr/lib/ruby/vendor_ruby/rubygems/defaults/operating_system.rb:10: warning: constant Gem::ConfigMap is deprecated
Fetching source index from https://rubygems.org/
Retrying fetcher due to error (2/4): Bundler::HTTPError Could not fetch specs from https://rubygems.org/ 

Para resolver, tive que desabilitar a ipv6 seguindo este tutorial:

https://cwesystems.com/?p=231

Seguindo esses poucos passos, o problema foi resolvido 😄

Objeto do rails sendo renderizado na tela

Se por acaso um objeto estiver sendo renderizado na tela junto com a estrutura html, verifique se a view apresenta algo como:

<%= @car_categories.each do |c| %>
	<div>
		<h2><%= link_to "Categoria #{c.name}", c %></h2>
		
		<dl>
			<dt>Valor da diaria</dt>
			<dd><%= number_to_currency c.daily_rate %></dd>
		</dl>
	</div>
<% end %>

Para resolver, retire o simbolo = de <%= @car_categories.each do |c| %>

Deixe-o assim: <% @car_categories.each do |c| %>

(<unknown>): did not find expected key while parsing a block mapping at line 110 column 4

Failure/Error: @car_model = CarModel.create(require_params)
     
     I18n::InvalidLocaleData:
       can not load translations from /home/diana/rental_cars/config/locales/pt-br.yml: #<Psych::SyntaxError: (<unknown>): did not find expected key while parsing a block mapping at line 110 column 4>

ou

     # ------------------
     # --- Caused by: ---
     # Psych::SyntaxError:
     #   (<unknown>): found a tab character that violate intendation while scanning a plain scalar at line 12 column 23
     #   /home/diana/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.6/lib/bootsnap/compile_cache/yaml.rb:13:in `input_to_storage'

Os arquivos com I18n sao muito exigentes com a formatacao, sao utilizados espacos ao invés da tecla tab. Eu recomendo copiar e colar da propria doc.

\#{customer.name}

Se estiver usando aspas simples para envolver a tag:

expect(page).to have_content('Cliente: #{customer.name}')

Mude para aspas duplas

expect(page).to have_content("Cliente: #{customer.name}")

Error install heroku

I try to install heroku to my raspberry ubuntu 16, but I have an error:

sudo snap install --classic heroku

error: cannot perform the following tasks:
- Run configure hook of "heroku" snap if present (run hook "configure": 
-----
/snap/heroku/3929/bin/run: 3: /snap/heroku/3929/bin/run: process.env.HEROKU_UPDATE_INSTRUCTIONS: not found
/snap/heroku/3929/bin/run: 5: /snap/heroku/3929/bin/run: Syntax error: word unexpected (expecting ")")
-----)

So, I try to install with npm;
npm install -g heroku

Before, I checked your version:

diana@diana-desktop:~/vagas$ heroku --version
heroku/7.42.0 linux-arm node-v10.2.0

SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL

$ bundle exec rails generate migration add_fields_to_car_model motorization fuel_type car_category:references
Apos criar uma amarracao de modelos e executar

$ rails db:migrate

Houve o seguinte erro:

SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL

Para resolver, va para o arquivo de migration que foi criado na amarracao e modifique:

add_reference :car_models, :car_category, null: false, foreign_key: true

para

add_reference :car_models, :car_category, foreign_key: true

Alem disso, insira belogs_to: car_category, no model car_model

e rode a migration novamente 😄

Render and/or redirect were called multiple times in this action.

Failure/Error: redirect_to :index
     
     AbstractController::DoubleRenderError:
       Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

The controller is like this:

	def search
		if params[:q].blank?
			@rentals = Rental.all
			flash.now[:alert] = 'Busca não pode ficar em branco'
			render :index		
		end 

		@rental = Rental.find_by(code: params[:q].upcase)

		if @rental.blank?
			@rentals = Rental.all
			flash.now[:alert] = "Nenhum resultado encontrado para: #{params[:q]}"
			render :index		
		end
	end

Change to resolve:

def search
		if params[:q].blank?
			@rentals = Rental.all
			flash.now[:alert] = 'Busca não pode ficar em branco'
			render :index		
		else 

		@rental = Rental.find_by(code: params[:q].upcase)

			if @rental.blank?
				@rentals = Rental.all
				flash.now[:alert] = "Nenhum resultado encontrado para: #{params[:q]}"
				render :index		
			end
		end
	end

Erro no teste ao redirecionar pagina

Failure/Error: expect(current_path).to eq customers_path
     
       expected: "/customers"
            got: "/"
     
       (compared using ==)

Quer dizer que estamos redirecionando para a rota errada, estou seja, estamos indo para a raiz ao inves do index de customers

Erro ao executar rspec #1

Ao executar o comando rspec para executar os testes, tive este erro:

     Failure/Error: <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
     
     ActionView::Template::Error:
       Webpacker can't find application in /home/diana/rentai-cars/rental-cars/public/packs-test/manifest.json. Possible causes:
       1. You want to set webpacker.yml value of compile to true for your environment
          unless you are using the `webpack -w` or the webpack-dev-server.
       2. webpack has not yet re-run to reflect updates.
       3. You have misconfigured Webpacker's config/webpacker.yml file.
       4. Your webpack configuration is not creating a manifest

Imagem nao carrega no Rails

Na pasta /rental_cars/app/assets/images devem estar todas as imagens do projeto. Exemplo:

/rental_cars/app/assets/images/logo.png

Para usa-las, basta colocar o nome da imagem e o rails reconhece:

Exemplo;

<div id="bglion"><%= image_tag("logo.png")%></div>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.