レビューモデルを作成していきます。
コマンド
rails g model Review project:references user:references comment:text created_at:datetime star:bigint
マイグレーション適用
rails db:migrate
「app\models\user.rb」ファイルに以下の記述を追加します。
記述追加 app\models\user.rb(5行目)
has_many :reviews
app\models\user.rb
class User < ApplicationRecord has_many :subscriptions has_many :projects, through: :subscriptions has_many :reviews # アバター画像表示用 include Gravtastic gravtastic # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :confirmable, :omniauthable #長さ50文字以下 入力必須 validates :full_name, presence: true, length: {maximum: 50} def self.from_omniauth(auth) user = User.where(email: auth.info.email).first if user 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\project.rb」ファイルに以下の記述を追加します。
1.記述追加 app\models\project.rb(6行目)
has_many :reviews
2.記述追加 app\models\project.rb(16行目)
def average_rating reviews.blank? ? 0 : reviews.average(:star).round(2) end
app\models\project.rb
class Project < ApplicationRecord has_many :tasks has_many :subscriptions has_many :users, through: :subscriptions has_many :reviews validates :name, presence: true, length: { maximum: 50 } validates :content, presence: true, length: { maximum: 500 } validates :price, presence: true, numericality: { only_integer: true } has_attached_file :image, styles: { medium: "680x300>", thumb: "170x75>" } validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ def average_rating reviews.blank? ? 0 : reviews.average(:star).round(2) end end