mysql - Use Foreign key in where clause in Rails -


i have 2 models 1 request , second passed

i have has_one association between requests , passed this

request.rb

 has_one :status 

status.rb

belongs_to :request

in status have boolean field namely "passed"

now want create

scope :passed -> where(request.status.passed=true) 

inside requests model.

here migration/schema database

class createrequests < activerecord::migration[5.0]      create_table :requests |t|       t.references :college, foreign_key: true       t.references :user , foreign_key: true       t.string :fullname       t.string :email       t.string :contact       t.string :reason       t.string :address_1       t.string :address_2       t.string :state       t.string :city       t.string :zipcode       t.string :enrollment_no       t.string :batch       t.string :course       t.text :extras         t.timestamps     end     add_index :requests , :email   end 

and status migration

create_table :statuses |t|   t.references :request, foreign_key: true   t.string :current_status, default: "reviewing application"   t.boolean :passed , default: false 

any suggestions ?

you can use this:

scope :passed, -> { joins(:status).where("statuses.passed = true") } 

took adaptation here: https://ducktypelabs.com/using-scope-with-associations/

this request model:

class request < activerecord::base   has_one :status   scope :passed, -> { joins(:status).where("statuses.passed = true") } end 

this status model

class status < activerecord::base   belongs_to :request end 

migration requests table:

class createrequests < activerecord::migration   def change     create_table :requests |t|       t.timestamps null: false     end   end end 

migration statuses table:

class createstatuses < activerecord::migration   def change     create_table :statuses |t|       t.boolean :passed, null: false, default: false       t.references :request       t.timestamps null: false     end   end end 

please note has_one :status call must declared before scope definition or won't work.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -