Rails 3:检索父模型属性等于搜索关键字的所有子记录

时间:2012-09-16 17:18:34

标签: ruby-on-rails ruby-on-rails-3 scope

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

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.workorder.branch =“350”。我想我可以做一个循环并以这种方式创建哈希,但我应该能够在查询中执行此操作吗?我应该尝试使用范围吗?

**更新

这是我最终使用的。工作得很好。

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

1 个答案:

答案 0 :(得分:20)

您想要的查询是

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

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

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

如果您要循环遍历工作程序,则应将连接更改为包含,因为此预先加载它们。

查询的rails指南对于此类事件http://guides.rubyonrails.org/active_record_querying.html

非常有用
相关问题