rails 4模型关联左连接validationid

我一直在争论这个,我想创建一个LEFT加入条件,所以我有一个优惠券模型,用户可以创建优惠券,但他们可能会或可能不会被分配到一个工作,当他们被分配时他们被认为执行。 我有这个设置为has_one :job优惠券模型上的add_reference :jobs, :coupon, index: trueadd_reference :jobs, :coupon, index: true索引,但这似乎是borked。 我认为今天我的大脑已被炸了……如果使用优惠券,我最好确认它被分配到有效的工作,这就是我使用索引的原因。

 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 

首先让我说你目前所拥有的东西并没有什么问题,而且实际上你的问题实际上并不清楚。

我实际上会以相反的方式对此进行建模,在coupons表上有job_id ,即:

 add_reference :coupons, :job, index:true 

和…

 class Coupon < ActiveRecord:Base belongs_to :job end 

最大的优点是你可以知道你的优惠券是否被执行而不查看任何其他表,如果job_idNULL然后它没有执行 - 而你现在如何拥有它你需要实际上做一个SELECT jobs表只是为了找出有coupon_id的记录

你的executed? 方法将变成如下:

 def executed? job_id.present? end