2016-03-04 83 views
0

我一直在爭取這一點,現在我想創建一個左連接條件,所以我有一個優惠券模型,用戶可以創建優惠券,但他們可能會或可能不會被分配給一份工作,當他們被分配時,他們被視爲被執行。我使用add_reference :jobs, :coupon, index: true索引在優惠券模型上設置爲has_one :job,但這看起來像是borked。我認爲我的大腦今天被炒了...如果使用優惠券,理想情況下我想確認它被分配到有效的工作,這就是爲什麼我正在使用索引。導軌4模型關聯左連接驗證ID

class CreateCoupons < ActiveRecord::Migration 
    def change 
    create_table :coupons do |t| 
     t.string :code, limit: 250, null: false 
     t.datetime :start_at, null: false 
     t.datetime :end_at, null: false 
     t.datetime :executed_at 
     t.datetime :deleted_at 
     t.timestamps null: false 
    end 

    add_reference :jobs, :coupon, index: true 
    add_index :coupons, :deleted_at 
    add_index :coupons, :code, unique: true 
    end 
end 

class CreateJobs < ActiveRecord::Migration 
    def change 
    create_table :jobs do |t| 
     t.string :title, limit: 50, null: false 
     t.string :slug, limit: 250, null: false 
     t.string :location, limit: 100, null: false 
     t.string :short_description, limit: 250, null: false 
     t.text :description, null: false 
     t.text :application_process, null: false 
     t.boolean :is_featured, default: false 
     t.datetime :start_at 
     t.datetime :end_at 

     t.timestamps null: false 
    end 

    add_index :jobs, :slug 
    end 
end 

和模型類...

class Coupon < ActiveRecord::Base 
    has_one :job 
end 

class Job < ActiveRecord::Base 
    belongs_to :coupon 
end 
+0

這個問題不清楚。例如,你有沒有任何理由在標題中提到了LEFT JOIN?什麼想要驗證? – Meier

+0

@Meier發佈的答案更清晰,我試圖驗證優惠券何時創建,稍後確保將其分配給有效的作業ID。我的後續思路在下面發佈的答案? –

回答

0

讓我說,沒有什麼真的錯了你有什麼現在開始,它實際上不是在這裏清楚你的問題是什麼。

我想這反過來實際上建模,在coupons爲表job_id,即:

add_reference :coupons, :job, index:true 

而且......

class Coupon < ActiveRecord:Base 
    belongs_to :job 
end 

與最大的好處是,你可以知道您的優惠券是否被執行或者沒有查看任何其他表格,如果job_idNULL那麼它不會被執行 - 而您現在如何擁有它,您需要在上實際執行SELECT操作表,只是找出是否有與coupon_id

executed?方法的記錄將成爲類似:

def executed? 
    job_id.present? 
end 
+0

你有它我認爲我現在正在測試這個,但是,你會將has_one移動到工作模式還是完全放棄它? –

+0

是的,可能將它移動到那裏,即使只是爲了記錄意圖。 – smathy

+0

酷,我現在要測試這個 –