2017-05-24 6 views
0

私はRailsを学んでおり、関連と移行ファイルを練習する練習をしています。Railsとの関連付けを試みようとしています

現在、ユーザー、オークションアイテム、および単価の間でモデルを作成しようとしています。

これまでのところ、以下の私が持っている移行ファイル用:

class CreateItem < ActiveRecord::Migration 
     def change 
     create_table :auction do |t| 
      t.string :item_name 
      t.string :condition 
      t.date :start_date 
      t.date :end_date 
      t.text :description 

     t.timestamps 
    end 
    end 
end 


class CreateBids < ActiveRecord::Migration 
    def change 
    create_table :bids do |t| 
     t.integer :user_id 
     t.integer :auction_id 

     t.timestamps 
    end 
end 
end 


    class CreateUsers < ActiveRecord::Migration 
    def change 
    create_table :users do |t| 
     t.string :email 
     t.string :username 
     t.string :password_digest 

     t.timestamps 
    end 
    end 

エンド

これらの次のモデルです。

class Bid < ActiveRecord::Base 
    belongs_to :bidder, class_name: "User", foreign_key: "bidder_id" 
    belongs_to :auction 
end 


class User < ActiveRecord::Base 
    has_many :bids 
    has_many :auctions, :foreign_key => 'bidder_id' 

    has_secure_password 
end 


class Auction < ActiveRecord::Base 
    belongs_to :seller, class_name: "User", foreign_key: :user_id 
    has_many :bids 
    has_many :bidders, through: :bids 
end 

任意の提案や意見は?私は現在、テーブルをテストしようとしていますが、オークションは動作していないようです... 特に、私のオークションテーブルはuser_idを見つけることができないため、ユーザーにはオークションがありません。

+1

「オークション」には何がありますか? 'bidder_id'はどこですか?それは 'user_id'ですか? –

+0

ええ、私は 'bidder_id'を削除し、それを 'user_id'に置き換えました。それは今働いているようですが、残りがうまくいくと思っています。 – user7496931

+0

答えをまとめて投稿しました。何か他のものが壊れた場合、別の質問を検索/投稿することができます。 –

答えて

0

foreign_keyは、_id(デフォルト)またはモデルの関連付けに使用される一意の属性を指します。

bidderモデルは表示されません。userモデルに関連付けられているため、user_idに置き換える必要があります。

あなたは将来の移行で物事を変更したい場合は、いつでも追加することができ、また次

class CreateGames < ActiveRecord::Migration[5.0] 
    def change 
    create_table :games do |t| 
     t.integer :total_time 
     t.references :version, foreign_key: true **#this is how a foreign key should be declared** 
     t.integer :total_points 

     t.timestamps 
    end 
    end 
end 

の線に沿ってより多くのものを使用したいの詳細belongs_to

0
class CreateBids < ActiveRecord::Migration 
    def change 
    create_table :bids do |t| 
     t.integer :user_id **do not think this is correct** 
     t.integer :auction_id **or this one** 

     t.timestamps 
    end 
end 
end 

のために参照してください。参考:

def change 
    add_reference :levels, :version, foreign_key: true 
    end 
関連する問題