Ruby on rails rails 4在查询执行后获取自定义列

Ruby on rails rails 4在查询执行后获取自定义列,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,我有以下疑问 @products = Product.where category_id: id 假设我有以下专栏 身份证 类别识别码 鼻涕虫 执行后,我需要单独使用slugnametest获取产品的id。只需使用限制1获取。有可能吗。如果是,我怎么做。您需要保留剩余的@产品吗 如果是: @products = Product.where(category_id: id) @the_product = @products.find { |p| p.slug == 'test' } # Note

我有以下疑问

@products = Product.where category_id: id
假设我有以下专栏

  • 身份证
  • 类别识别码
  • 鼻涕虫

  • 执行后,我需要单独使用
    slug
    name
    test
    获取产品的
    id
    。只需使用
    限制1
    获取。有可能吗。如果是,我怎么做。

    您需要保留剩余的
    @产品吗

    如果是:

    @products = Product.where(category_id: id)
    @the_product = @products.find { |p| p.slug == 'test' }
    # Note: This will iterate over objects in memory. Depending on 
    # how many products you have per category, it may be more efficient 
    # to simply make another query to the database, as with the code below.
    
    如果没有:

    @products = Product.where(category_id: id, slug: 'test').limit(1)