问题
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
And model classes...
class Coupon < ActiveRecord::Base
has_one :job
end
class Job < ActiveRecord::Base
belongs_to :coupon
end
回答1:
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.
I would actually model this the other way around, having job_id on the coupons table, ie.:
add_reference :coupons, :job, index:true
And...
class Coupon < ActiveRecord:Base
belongs_to :job
end
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
Your executed? method would become something like:
def executed?
job_id.present?
end
来源:https://stackoverflow.com/questions/35807553/rails-4-model-association-left-join-validate-id