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

时间:2017-08-18 12:36:15

标签: mysql sql ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我有2个型号 1是请求,第二个是

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

Request.rb

 has_one :status

status.rb

belongs_to :request

状态中的

我有一个布尔字段,即"传递"

现在我想创建一个

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

在我的请求模型中。

这是我的数据库的迁移/架构

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

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用:

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

请求表的迁移:

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

状态表的迁移:

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调用,否则它将无法正常工作。