ユーザー(出品者)がサービス(商品)を出品し、別のユーザー(購入者)がそれを購入できるというケースを想定した場合、以下の考え方で正しいでしょうか?誤りがあればご指摘頂けますと幸甚です。
###前提
・ユーザー(出品者)とサービス (商品): 1対多の関連付け
・サービス(商品)とユーザー(購入者) : 多対多の関連付け *1つのサービス(商品)に複数のユーザー(購入者)が購入できる前提。
・ユーザーは出品者にも購入者にもなれる : 出品者と購入者は同じmodel
##モデル(正しいでしょうか?)
・上記前提を元にすると、必要となるmodel
はUser
とProduct
とEntry
(productとそれを買うuser(購入者))を多対多の関連付けで使用する中間テーブル)の3つ
・すなわち、以下のイメージ
user
(1)<-> (多)product
(1) <-> (多)entry
(多) <->(1) user
###各モデルのテーブル(migration file) *単純化してます
User
ruby
1#User 2class CreateUsers < ActiveRecord::Migration[5.0] 3 def change 4 create_table :users do |t| 5 t.string :email, null: false # メールアドレス 6 t.string :family_name # 姓 7 t.string :given_name # 名 8 t.string :address # 住所 9 t.text :user_profile # プロフィール 10 t.string :hashed_password # パスワード 11 12 t.timestamps 13 end 14 end 15end 16 17#Product 18class CreateProducts < ActiveRecord::Migration[5.0] 19 def change 20 create_table :products do |t| 21 t.references :user #外部キー 22 t.integer :price #価格 23 t.string :title #タイトル 24 t.datetime :posted_at #商品投稿日 25 t.binary :data #写真 26 t.timestamps null: false 27 end 28 end 29end 30 31#Entry 32class CreateEntries < ActiveRecord::Migration[5.0] 33 def change 34 create_table :entries do |t| 35 t.references :product, null: false 36 t.references :user, null: false 37 t.timestamps 38 end 39 end 40end 41
###各モデルの書き方
ruby
1#Userモデル 2class User < ApplicationRecord 3 has_many :products, dependent: :destroy 4 has_many :applied_products, through: :entries, dependent: :destroy, source: :product 5 has_many :entries, dependent: :destroy 6end 7 8#Productモデル 9class Product < ApplicationRecord 10 belongs_to :user 11 has_many :entries, dependent: :destroy 12 has_many :applicants, through: :entries, source: :user 13end 14 15#Entryモデル 16class Entry < ApplicationRecord 17belongs_to :applied_products, class_name: "Product", foreign_key: "product_id" 18belongs_to :applicants, class_name: "User", foreign_key: "user_id" 19end 20 21
回答2件
あなたの回答
tips
プレビュー