学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

Rails6.0 | 仕事売買サイトの構築 | 19 | 仕事モデル

[18]プロフィールページ << [ホームに戻る] >> [20]仕事コントローラ


仕事のモデルを作成します。


コマンド(4つ)
rails g model Category name --no-test-framework


一文です。
rails g model Gig title video active:boolean has_single_pricing:boolean user:references category:references --no-test-framework


一文です。
rails g model Pricing title description:text delivery_time:bigint price:bigint pricing_type:bigint gig:references --no-test-framework


アクションテキストのインストール
rails action_text:install


「db\migrate\20200708052213_create_gigs.rb」ファイルの記述を以下のように変更します。


記述更新 db\migrate\20200708052213_create_gigs.rb
6行目と7行目に「, default: false」の記述を追加しています。

class CreateGigs < ActiveRecord::Migration[6.0]
  def change
    create_table :gigs do |t|
      t.string :title
      t.string :video
      t.boolean :active, default: false
      t.boolean :has_single_pricing, default: false
      t.references :user, null: false, foreign_key: true
      t.references :category, null: false, foreign_key: true

      t.timestamps
    end
  end
end



コマンド マイグレーション適用
rails db:migrate


「app\models\gig.rb」ファイルを以下の内容に更新します。



app\models\gig.rb

class Gig < ApplicationRecord
  belongs_to :user
  belongs_to :category

  has_many :pricings
  has_many_attached :photos
  has_rich_text :description

  accepts_nested_attributes_for :pricings

  validates :title, presence: { message: '空白にはできません' }
end



「app\models\category.rb」ファイルを以下の内容に更新します。


app\models\category.rb

class Category < ApplicationRecord
    has_many :gigs
end



「app\models\user.rb」ファイルに以下の記述を追加します。


記述追加 app\models\user.rb(3行目)

has_many :gigs



app\models\user.rb

class User < ApplicationRecord

  has_many :gigs

  has_one_attached :avatar

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, 
         :omniauthable, :confirmable

  validates :full_name, presence: true, length: {maximum: 50}      

  def self.from_omniauth(auth)
    user = User.where(email: auth.info.email).first

    if user
      if !user.provider
        user.update(uid: auth.uid, provider: auth.provider, image: auth.info.image)
      end
      return user
    else
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.email = auth.info.email
        user.password = Devise.friendly_token[0, 20]
        user.full_name = auth.info.name   # ユーザーモデルに名前があると仮定
        user.image = auth.info.image # ユーザーモデルに画像があると仮定

        user.uid = auth.uid
        user.provider = auth.provider

      end
    end
  end
  
end



「app\models\pricing.rb」ファイルを以下の内容に更新します。


app\models\pricing.rb

class Pricing < ApplicationRecord
  belongs_to :gig
  enum pricing_type: [:basic, :standard, :premium]
end



↓↓クリックして頂けると励みになります。


[18]プロフィールページ << [ホームに戻る] >> [20]仕事コントローラ