GithubHelp home page GithubHelp logo

progate-ruby-on-rails's Introduction

progate Ruby on Rails5

command history

$ gem install rails -v 7.0.3

$ rails new tweet_app
$ cd tweet_app
$ rails server
http://localhost:3000/


$ rails generate controller home top
http://localhost:3000/home/top

$ rails generate controller posts index
http://localhost:3000/posts/index

$ rails g model post content:text
$ rails db:migrate


$ rails console
Loading development environment (Rails 5.0.3)
[1] pry(main)> post = Post.new(content: "aaa")
=> #<Post:0x00005617edf0c098 id: nil, content: "aaa", created_at: nil, updated_at: nil>
[2] pry(main)> post.save
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "posts" ("content", "created_at", "updated_at") VALUES (?, ?, ?)  [["content", "aaa"], ["created_at", "2022-10-10 13:44:47.148716"], ["updated_at", "2022-10-10 13:44:47.148716"]]
   (6.8ms)  commit transaction
=> true
irb(main):003:0> post = Post.first
  Post Load (0.4ms)  SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT ?  [["LIMIT", 1]]
=> #<Post:0x00007f257219e030 id: 1, content: "aaa", created_at: Thu, 13 Oct 2022 13:25:28.574698000 UTC +00:00, updated_at: Thu, 13 Oct 2022 13:25:28.574698000 UTC +00:00>
irb(main):004:0> post.content
=> "aaa"

irb(main):010:0> posts = Post.all
  Post Load (0.1ms)  SELECT "posts".* FROM "posts"
=>
[#<Post:0x00007f2572a966d8 id: 1, content: "aaa", created_at: Thu, 13 Oct 2022 13:25:28.574698000 UTC +00:00, updated_at: Thu, 13 Oct 2022 13:25:28.574698000 UTC +00:00>,
...


irb(main):005:0> quit

$ rails g model User name:string email:string
$ rails db:migrate
$ rails console
Loading development environment (Rails 7.0.4)
irb(main):001:0> user = User.new(name:"にんじゃわんこ",email:"[email protected]")
=> #<User:0x00007fe0400505c8 id: nil, name: "にんじゃわんこ", email: "[email protected]", created_at: nil, updated_at: nil>
irb(main):002:0> user.save
  TRANSACTION (0.1ms)  begin transaction
  User Create (0.3ms)  INSERT INTO "users" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["name", "にんじゃわんこ"], ["email", "[email protected]"], ["created_at", "2022-10-16 02:31:27.207029"], ["updated_at", "2022-10-16 02:31:27.207029"]]
  TRANSACTION (10.8ms)  commit transaction
=> true
irb(main):003:0> quit

$ rails g controller users index

データベースに変更を加える手順
- マイグレーションファイルのみを作成する
- マイグレーションファイルの内容をデータベースに反映させる

$ rails g migration add_image_name_to_users
できたファイを編集
$ rails db:migrate

ファイルの作成
$ rails console
Loading development environment (Rails 5.0.3)
[1] pry(main)> File.write("public/sample.txt", "Hello World")
=> 11
[2] pry(main)> /opt/progate/bin/rails:16:in `system': Interrupt
        from /opt/progate/bin/rails:16:in `run_in_app'
        from /opt/progate/bin/rails:59:in `<main>'


パスワードカラムの追加
$ rails g migration add_password_to_users
$ rails db:migrate


postsテーブルにuser_idカラムを追加する
$ rails g migration add_user_id_to_posts
$ rails db:migrate


likeテーブルを作成する
$ rails g model Like user_id:integer post_id:integer
$ rails db:migrate


gemとは、RubyやRailsでプログラミングをする際に「よく使う機能」をパッケージ化したものです。
今回はbcryptという「ハッシュ化するgem」を使います。
Gemfileに追加して
$ bundle install


password_digestカラムを追加してpasswordカラムを消す
$ rails g migration change_users_columns
$ rails db:migrate

password_digestカラムにハッシュ化されたパスワードを保存するためには、今まで通りpasswordに値を代入します。
こうすることで、has_secure_passwordによってpasswordに代入された値がハッシュ化され、password_digestカラムに保存されます。
このため、既にあるpasswordに関するコードを変更する必要はありません。

memo

lesson4のlink_toでmethod postを指定してもgetになってしまった

lesson4 のshow.html.rbの以下の箇所

  <%= link_to("削除", "/posts/#{@post.id}/destroy", {method: "post"}) %>

はrailsのバージョンが

$ rails -v
Rails 7.0.4

ではgetメソッドにされてしまった。以下の記事を参考にして

以下のコマンドを実行

$  rails importmap:install
Add Importmap include tags in application layout
File unchanged! The supplied flag value not found!  app/views/layouts/application.html.erb
Create application.js module as entrypoint
    conflict  app/javascript/application.js
Overwrite /home/******/Study/progate-ruby-on-rails/tweet_app/app/javascript/application.js? (enter "h" for help) [Ynaqdhm] Y
       force  app/javascript/application.js
Use vendor/javascript for downloaded pins
       exist  vendor/javascript
   identical  vendor/javascript/.keep
Ensure JavaScript files are in the Sprocket manifest
File unchanged! The supplied flag value not found!  app/assets/config/manifest.js
Configure importmap paths in config/importmap.rb
    conflict  config/importmap.rb
Overwrite /home/*******/Study/progate-ruby-on-rails/tweet_app/config/importmap.rb? (enter "h" for help) [Ynaqdhm]
       force  config/importmap.rb
Copying binstub
   identical  bin/importmap
$  rails turbo:install stimulus:install
Import Turbo
      append  app/javascript/application.js
Pin Turbo
      append  config/importmap.rb
Run turbo:install:redis to switch on Redis and use it in development for turbo streams
Create controllers directory
       exist  app/javascript/controllers
   identical  app/javascript/controllers/index.js
   identical  app/javascript/controllers/application.js
   identical  app/javascript/controllers/hello_controller.js
Import Stimulus controllers
      append  app/javascript/application.js
Pin Stimulus
Appending: pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true"
      append  config/importmap.rb
Appending: pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
      append  config/importmap.rb
Pin all controllers
Appending: pin_all_from "app/javascript/controllers", under: "controllers"
      append  config/importmap.rb

さらにlink_toを以下に書き換えたら動いた。

  <%= link_to("削除", "/posts/#{@post.id}/destroy", data: { turbo_method: :post }) %>

lesson5でrails7ではedit.html.erbにエラーメッセージが表示されなかった。

Rails7.0からデフォルトでTurboが導入されており、バリデーションのエラーメッセージを表示させるためには上記の記述を追加する必要があるようです。

Turboとは?

lesson8でのapplication_controller.rb書き方

これがお手本の書き方。これだとRails7では動かんかった

class ApplicationController < ActionController::Base
  # before_actionにset_current_userメソッドを指定してください
      before_action :set_current_user

  # set_current_userメソッドを定義してください
    def set_current_user
        @current_user = User.find_by(id: session[:user_id])
    end

end

↓ 変更

class ApplicationController < ActionController::Base
    before_action :set_current_user

    private 

    def set_current_user
        @current_user = User.find_by(id: session[:user_id])
    end
end

progate-ruby-on-rails's People

Contributors

mo3g4u avatar

Watchers

 avatar

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.