Rails 4 model associations left join validate id

I'm struggling a bit for this, 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 the task, when they are assigned they are considered fulfilled. I had this setting as has_one :job on a coupon model with the index add_reference :jobs, :coupon, index: true , but it looks like borked. I think my brain is fried today ... If a coupon is used, I would ideally want to confirm that it is assigned to a valid job, so I worked 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 
0
ruby ruby-on-rails activerecord model-view-controller
Mar 04 '16 at 22:55
source share
1 answer

Let me start with the fact that there is nothing wrong with what you have at the moment, and in fact it is not entirely clear what your problem is.

I would really simulate this the other way around, having job_id in the coupons table, job_id .:

 add_reference :coupons, :job, index:true 

BUT...

 class Coupon < ActiveRecord:Base belongs_to :job end 

The biggest advantage is that you can find out if your coupon is running or not without looking at any other table, if job_id is NULL then it is not executed - whereas now you really have it do a SELECT in the jobs table to see if there was a record with this coupon_id

executed? your method executed? will become something like:

 def executed? job_id.present? end 
0
Mar 04 '16 at 23:04
source share



All Articles