LoginSignup
1
2

More than 3 years have passed since last update.

アソシエーションの基礎 current_user

Posted at

ここでやりたいこと

  1. productを作った人とサイインしている人は常に同じ人物である
    • create アクションをするときにcurrent_idと紐づいたproductを保存したい
  2. ProductモデルとUserモデルとcurrent_userをわかりやすく紐付けたい。下記のコードをアソシエーションを用いて簡単にしたい。

コメントアウトしているのは最初に僕が1のことをやろうとして試したこと。この時は=をイコールとして考えていました。

def create
    @product = Product.new(product_params)
    #current_user.id = @product.user.id
    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

今回触れること

  • =について
  • current_userの型について。そもそも型って何?
  • アソシエーションを用いた紐付け

「=」はイコールというよりは右辺を左辺に代入するという意味がつよい!

なのでこのコードも current_user持っているidをProductモデルのuser_idに代入すると考えられる。

@product.user_id = current_user.id 

current_userの型(モデル)って何んだ?

型はクラスをつけて書くことで新しいものを作れる

型の例

class ApplicationController < ActionController::Base
end
class Member < ApplicationRecord
end

stringやintegerも型ですね

ハッシュも型の一つで、型を確かめるにはclass.nameを打ってみるといいと思います!

a = "aaa"
=> "aaa"
> a.class.name
=> "String"

current_userの型を確かめたい!ただcurrent_userはrails cでは確認できないので、コントローラーなどで確認することにします。

current_userが使われているアクションなどで、 適当に 

a = current_user.class.name
puts a

とかやるとターミナルにcurrent_userの型が表示されます。ちなみにcurrent_userの型はUserでした!理解していなかった、、つまりcurrent_userはUserモデルなんですね

これがわかるとアソシエーションを結びつけることができる。(UserモデルとProductモデルがhas_many :products, belongs_to :user になっている前提。またProductモデルにはuser_idがあり、リレーションを呼び出せる。)

createを実際に変えてみる

この1行でいいんですね。current_userのidをProductモデルのuser_idに代入し、newする 
@product = current_user.products.new(product_params)
ちなみにアソシエーションで持ってこれるのはidのみです。

def create
    @product = current_user.products.new(product_params)
    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end
1
2
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
1
2