Rails 3:检索父模型属性等于搜索键的所有子记录 [英] Rails 3: Retrieve all child records where parent model attribute equals search key

查看:20
本文介绍了Rails 3:检索父模型属性等于搜索键的所有子记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个查询,只返回没有序列号的资产,其中工单分支等于一个数字.

I want to do a query that returns only the assets that do not have a serial number where the workorder branch equals a number.

class Workorder < ActiveRecord::Base
    belongs_to :user
    has_many :assets

    scope :current_branch, where("branch=350").order("wo_date ASC")
end

class Asset < ActiveRecord::Base
    belongs_to :workorder

    scope :needs_serial, :conditions =>  {:serial => ""}
end

class AssetsController < ApplicationController
    def index
        @assets_needing_serial=???
    end
end

所以我想要一个 :assets 的哈希值,其中 assets.workorder.branch="350".我想我可以做一个循环并以这种方式创建哈希,但我应该能够在查询中做到这一点吗?我应该为此尝试使用范围吗?

So I want a hash of :assets where the assets.workorder.branch="350". I think I could do a loop and create the hash that way but should I be able to do this in a query? Should I be trying to use scopes for this?

**更新

这是我最终使用的.效果很好.

This is what I ended up using. Worked great.

@assets = Asset.joins(:workorder).where('workorders.branch=350').order('workorders.wo_date ASC')

推荐答案

您想要做的查询是

Asset.joins(:workorder).where('workorders.branch = 325')

所以你可以制作一个这样的范围:

So you can make a scope like this:

scope :with_workorder_branch, lambda { |branch| joins(:workorder).where('workorders.branch = ?', branch) }

如果您要遍历工单,您应该将联接更改为包含,因为这会急切加载它们.

If you're going to be looping through the workorders, you should change the joins to includes as this eager loads them.

rails 查询指南对这类事情非常有帮助 http://guides.rubyonrails.org/active_record_querying.html

The rails guide to queries is very helpful for this sort of thing http://guides.rubyonrails.org/active_record_querying.html

这篇关于Rails 3:检索父模型属性等于搜索键的所有子记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆