Rails 3: Retrieve all child records where parent model attribute equals search key

走远了吗. 提交于 2019-12-09 06:02:49

问题


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

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?

**Update

This is what I ended up using. Worked great.

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

回答1:


The query you would want to do is

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.

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



来源:https://stackoverflow.com/questions/12448983/rails-3-retrieve-all-child-records-where-parent-model-attribute-equals-search-k

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!