0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsチュートリアル学習メモ2

0
Last updated at Posted at 2019-11-29

データ更新(rails cから)

[1] pry(main)> post = Post.find_by(id: 1)
[2] pry(main)> post.content = "ああああああ"
[3] pry(main)> post.save

データの削除(rails cから)

[1] pry(main)> post = Post.find_by(id: 1)
[2] pry(main)> post.destroy
[3] pry(main)> post.save

link_toでmethodを指定する

link_to("文言", "パス", {method: "post"})

modelにvalidationを設定

modes/post
validates :content,  {presence: true, length: {maximum: 100}}
// presenceはカラムが存在するか確認する
uniqueness: true // データ上の重複を防いでくれる

renderメソッド

renderメソッドを使うと、redirect_toメソッドを使った場合と違い、そのアクション内で定義した@変数をビューでそのまま使える。

エラーメッセージはRails側で自動で保存される

@post.errors.full_messages

view側でのエラーメッセージ表示

test.html.erb
          <% @post.errors.full_messages.each do |message| %>
            <div class="form-error">
              <%= message %>
            </div>
          <% end %>

ん、railsってメッセージデフォルトで予測してくれて入っちゃってる感じ?

フラッシュメッセージ

flash[:notice] = "投稿を編集しました"

マイグレーションファイルだけを作成

$ rails g migration migration_file_name

画像を表示(public配下の画像を表示させる)

<img src="/user_images/<%= user.image_name %>">

画像をアップロードする際のformの書き方

form_tag("パス", {multipart: true}) do

画像を保存

[1] pry(main)> File.write("public/sample.txt", "Hello World")
[1] pry(main)> File.write("ファイルパス", "ファイルの中身")

画像をControllerから保存

    if params[:image]
      @user.image_name = "#{@user.id}.jpg"
      image = params[:image]
      File.binwrite("public/user_images/#{@user.image_name}", image.read)
    end

image.read でPOSTされた画像データをopenして保存する

セッション

session[:name]

GET, POSTの使い分け

GET => DBの更新がない
POST => DBの更新がある。セッションの修正がある

Appication_controllerに共通の変数を定義する

class ApplicationController < ActionController::Base
  before_action :set_current_user
  def set_current_user
    @current_user = User.find_by(id: session[:user_id])
  end
end

これはミドルウェアっていう認識でいいのかな?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?