Rails范围过滤/从关联

时间:2015-11-18 07:43:34

标签: ruby-on-rails ruby rails-activerecord

我在PublicKey和PublicKeyRole之间有一对一的关联。 PublicKey模型有一列role_id,而PublicKeyRole模型有role列,这是一个字符串,例如'super'

我希望能够通过url查询参数搜索角色字符串,例如; https://api.domain.com/public_keys?role=admin。我在PublicKey模型上尝试了这个,但我不确定将查询传递到哪里:

scope :filter_by_role, lambda { |query|
  joins(:public_key_role).merge(PublicKeyRole.role)
}

以下是我的模特:

class PublicKey < ActiveRecord::Base
  belongs_to :user
  belongs_to :public_key_role, foreign_key: :role_id

  def self.search(params = {})
    public_keys = params[:public_key_ids].present? ? PublicKey.where(id: params[:public_key_ids]) : PublicKey.all
    public_keys = public_keys.filter_by_role(params[:role]) if params[:role]

    public_keys
  end
end

class PublicKeyRole < ActiveRecord::Base
  has_one :public_key
end

另外,这是我的测试:

describe '.filter_by_role' do
    before(:each) do
      @public_key1 = FactoryGirl.create :public_key, { role_id: 1 }
      @public_key2 = FactoryGirl.create :public_key, { role_id: 2 }
      @public_key3 = FactoryGirl.create :public_key, { role_id: 1 }
    end

    context "when a 'super' role is sent" do
      it 'returns the 2 matching public keys results' do
        expect(PublicKey.filter_by_role('super').size).to eq(2)
      end

      it 'returns the matching public keys' do
        expect(PublicKey.filter_by_role('super').sort).to match_array([@public_key1, @public_key3])
      end
    end
  end

更新

我在我的规范中遗漏了以下内容,@ lcguida的答案有效。

FactoryGirl.create :public_key_role, { id: 1, role: 'super' }

1 个答案:

答案 0 :(得分:1)

the docs你有一些例子。您可以搜索将查询传递给PublicKeyRole关系的关系:

scope :filter_by_role, lambda { |query|
  joins(:public_key_role).merge(PublicKeyRole.where(role: query))
}

如果你想要一个字符串搜索(如LIKE):

scope :filter_by_role, lambda { |query|
  joins(:public_key_role).merge(PublicKeyRole.where(PublicKeyRole.arel_table[:role].matches(query)))
}