在 Rails 中的 where 子句中使用外键

Use Foreign key in where clause in Rails

我有2个模型 1 是请求,第二个是通过

我在请求之间有一个 has_one 关联并像这样传递

Request.rb

 has_one :status

status.rb

belongs_to :request

在状态中我有一个布尔字段即 "passed"

现在我想创建一个

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

在我的请求模型中。

这是我的数据库migration/schema

class CreateRequests < ActiveRecord::Migration[5.0]

    create_table :requests do |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

这是我的状态迁移

create_table :statuses do |t|
  t.references :request, foreign_key: true
  t.string :current_status, default: "Reviewing Application"
  t.boolean :passed , default: false

有什么建议吗?

你可以使用这个:

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

改编自此处:https://ducktypelabs.com/using-scope-with-associations/

这是请求模型:

class Request < ActiveRecord::Base
  has_one :status
  scope :passed, -> { joins(:status).where("statuses.passed = true") }
end

这是状态模型

class Status < ActiveRecord::Base
  belongs_to :request
end

迁移请求 table:

class CreateRequests < ActiveRecord::Migration
  def change
    create_table :requests do |t|
      t.timestamps null: false
    end
  end
end

迁移状态table:

class CreateStatuses < ActiveRecord::Migration
  def change
    create_table :statuses do |t|
      t.boolean :passed, null: false, default: false
      t.references :request
      t.timestamps null: false
    end
  end
end

请注意,has_one :status 调用必须在作用域定义之前声明,否则将不起作用。