2016-03-04 77 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

酷,我现在要测试这个 –