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

Jas*_*ump 9 scope ruby-on-rails ruby-on-rails-3

我想做一个查询,只返回没有序列号的资产,其中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
Run Code Online (Sandbox Code Playgroud)

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

**更新

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

@assets = Asset.joins(:workorder).where('workorders.branch=350').order('workorders.wo_date ASC')
Run Code Online (Sandbox Code Playgroud)

Edw*_*ard 20

您想要做的查询是

Asset.joins(:workorder).where('workorders.branch = 325')
Run Code Online (Sandbox Code Playgroud)

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

scope :with_workorder_branch, lambda { |branch| joins(:workorder).where('workorders.branch = ?', branch) }
Run Code Online (Sandbox Code Playgroud)

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

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