私はRuby On Railsを学校で購入/再販プラットフォームプロジェクトを開始しています。私はリレーショナルモデルからそれらを翻訳しようとすると私のモデルに問題があります。データベースモデルをRuby On Railsのモデルに翻訳する
まず、私は自分のデータベースをモデル化しました。ここでは実体関連モデルを単純化されています
私は、リレーショナルモデルでそれを翻訳しました:
最後に、私は、RubyでRailsの中でそれを実装しました。
class Client < ApplicationRecord
attr_accessor :name
validates :name, :presence => true
has_many :purchasings, :dependent => :destroy
has_many :sellers, :through => :purchasings
has_many :articles, :through => :purchasings
end
私はモデルの販売を実施してきました:
class Seller < ApplicationRecord
attr_accessor :name
validates :name, :presence => true
has_many :purchasings, :dependent => :destroy
has_many :sellers, :through => :purchasings
has_many :articles, :through => :purchasings
end
私はモデル条
class Article < ApplicationRecord
attr_accessor :quantity
validates :quantity, :presence => true
has_one :purchasing, :dependent => :destroy
has_one :client, :through => :purchasings
has_one :seller, :through => :purchasings
end
を実施してきた私は、モデルのクライアントを実装しました
私はモデルの購入実装しました:私は、私が上で次のコードを実行するときので、これは間違っている知っている
class CreatePurchasing < ActiveRecord::Migration[5.1] def change [...] add_index :purchasings, :client_id add_index :purchasings, :seller_id add_index :purchasings, :article_id add_index :purchasings, [:client_id, :seller_id], :unique => true end def down [...] end end
:
class Purchasing < ApplicationRecord
attr_accessor :client_id, :seller_id, :article_id
belongs_to :client, :class_name => "Client"
belongs_to :seller, :class_name => "Seller"
belongs_to :article, :class_name => "Article"
validates :client_id, :presence => true
validates :seller_id, :presence => true
validates :article_id, :presence => true
end
を私は購入のデータベースの移行を変更しましたRailsコンソール:
cl1 = Client.create(:name => "John")
cl2 = Client.create(:name => "James")
sel1 = Seller.create(:nom => "Jack")
sel2 = Seller.create(:nom => "Jil")
a1 = Article.create(:quantity => 5)
p1 = Purchasing.new(:client => cl1, :client_id => cl1.id, :seller => sel1, :seller_id => sel1.id, :article => a1, :article_id => a1.id)
p1.save
p2 = Purchasing.new(:client => cl2, :client_id => cl2.id, :seller => sel1, :seller_id => sel1.id, :article => a1, :article_id => a1.id)
p2.save
p2.save
はtrueを返します。同一の売り手で販売することはできず、異なる2つの顧客によって購入することもできません。
質問はありますか? –
また、attr_accessorsを削除してください。彼らはあなたが思っていることをしていない。 –
@SergioTulentsevまあ、私のテストは私が期待しているものを生成しないので、解決策を探しています(p2.saveは、記事がクライアントによって既に購入されているためfalseを返します)。 – titimlb