Rails 4模型关联左联接验证ID [英] rails 4 model association left join validate id
问题描述
我已经为此进行了一段时间的争执,我想创建一个LEFT联接条件,所以我有一个Coupon模型,用户可以创建优惠券,但是当他们被分配时,他们可能会分配也可能不会分配给工作他们被认为已执行.我在带有add_reference :jobs, :coupon, index: true
索引的优惠券模型上将其设置为has_one :job
,但这似乎令人厌烦.我认为今天我的大脑已经炸了……如果使用优惠券,我理想地想确认它是否已分配给有效工作,这就是我使用索引的原因.
I have been battling this for a bit now, I want to create a LEFT join condition, so I have a Coupon model, users can create coupons but they may or may not be assigned to a job, when they are a assigned they are considered executed. I had this setup as has_one :job
on the coupon model with a add_reference :jobs, :coupon, index: true
index, but this seems borked. I think my brain is fried today… If coupon is used I would ideally like to confirm that it is assigned to valid job, which is why I was working with the index.
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
推荐答案
首先,我要说的是您目前所拥有的并没有什么真正的问题,实际上还不清楚您的问题出在哪里.
Let me start by saying that there's nothing really wrong with what you've got currently, and it's not actually clear what your problem here is.
我实际上将对此建模,将job_id
放在coupons
表上,即:
I would actually model this the other way around, having job_id
on the coupons
table, ie.:
add_reference :coupons, :job, index:true
然后...
class Coupon < ActiveRecord:Base
belongs_to :job
end
最大的优点是,无需查看任何其他表就可以知道是否执行了优惠券,如果job_id
为NULL
则不执行该优惠券-现在,您需要如何获取优惠券实际上在jobs
表上执行SELECT只是为了找出是否存在带有该coupon_id
The biggest advantage with that is that you can know whether your coupon is executed or not without looking at any other table, if job_id
is NULL
then it's not executed - whereas how you have it now you'd need to actually do a SELECT on the jobs
table just to find out if there was a record with that coupon_id
您的executed?
方法将变为:
def executed?
job_id.present?
end
这篇关于Rails 4模型关联左联接验证ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!