rails 4模型关联左连接validationid
我一直在争论这个,我想创建一个LEFT加入条件,所以我有一个优惠券模型,用户可以创建优惠券,但他们可能会或可能不会被分配到一个工作,当他们被分配时他们被认为执行。 我有这个设置为has_one :job
优惠券模型上的add_reference :jobs, :coupon, index: true
与add_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_id
是NULL
然后它没有执行 - 而你现在如何拥有它你需要实际上做一个SELECT jobs
表只是为了找出有coupon_id
的记录
你的executed?
方法将变成如下:
def executed? job_id.present? end
- ActiveRecord :: StatementInvalid:ArgumentError:负字符串大小(或大小太大):SELECT * FROM
- 在进行ActiveRecord :: Base计数时如何按计数desc进行排序?
- Rails:有很多通过关联 – 找到AND条件,而不是OR条件
- 根据多个列删除重复记录
- Rails模型的默认条件
- Rails ActiveRecord:是否可以组合:include和:conditions查询?
- ActiveRecord:inverse_of不适用于has_many:通过on上的连接模型
- Mysql ::错误:重复条目
- Ruby On Rails – Geocoder – 接近条件