2013-02-14 3 views
17

同じテーブルを参照する2つのフィールドを持つ移行を作成するにはどうすればよいですか?私はテーブルAと画像を持っています。 A.image1_idは画像を参照し、A.image2_idは画像も参照します。イメージは2つしかありませんが、多くはありません。私は同じモデルへの複数の参照を1つのテーブルに追加するにはどうすればよいですか? Ruby/Rails

class AddFields < ActiveRecord::Migration 
    def change 
    change_table(:ticket) do |t| 
     t.references :image1_id 
     t.references :image2_id 
    end 
    end 
end 

を使用している場合、私はそれが最後に別の_idを追加すると、おそらく「画像」モデルを使用することを知ることができませんので、それが動作するとは思いません。私も考えた

change_table(:ticket) do |t| 
    t.references :image 

しかし、私はそれらの2つを追加するには?私はまた、

create_table :images do |t| 
    t.belongs_to :ticket 
    t.string :file 

を追加することを考えました。しかし、私はわずか2、多くはないが欲しい、これがticket.image1またはticket.image2のように、チケットから画像を取得できるように表示されません。

この文書のhttp://apidock.com/rails/v3.2.8/ActiveRecord/ConnectionAdapters/SchemaStatements/change_tableによると、t.referencesはいずれも引数を取っていないようです。

change_table(:suppliers) do |t| 
    t.references :company 
end 
+0

私は今、1つのリレーションを作成し、 'before_save'フィルタまたは' validate:my_validation'を使用してリレーションを2レコードに制限すると思います。 – Chloe

答えて

28

あなたは、単にあなたの移行でadd_column方法でこれを行うと、あなたのクラスで適切な団体に設定することができます。このブログの記事

class AddFields < ActiveRecord::Migration 
    def change 
    add_column :tickets, :image_1_id, :integer 
    add_column :tickets, :image_2_id, :integer 
    end 
end 

class Ticket < ActiveRecord::Base 
    belongs_to :image_1, :class_name => "Image" 
    belongs_to :image_2, :class_name => "Image" 
end 

class Image < ActiveRecord::Base 
    has_many :primary_tickets, :class_name => "Ticket", :foreign_key => "image_1_id" 
    has_many :secondary_tickets, :class_name => "Ticket", :foreign_key => "image_2_id" 
end 

を、Creating Multiple Associations with the Same Table、より詳しく説明します。

+3

右、 't.references:x'は' t.column:x_id、:integer'または 't.integer:x_id'の省略形です。 –

+0

'ticket.image1'を使うためにt.referencesは必要ありませんか? – Chloe

+0

@muistooshortと同様に、それは便利な方法です。あなたのものは、おそらく異なるヘルパーメソッドを使う方が良い特別なケースです。 – rossta

関連する問題