【问题标题】:Rails 3: Retrieve all child records where parent model attribute equals search keyRails 3:检索父模型属性等于搜索键的所有子记录
【发布时间】:2012-09-09 01:30:21
【问题描述】:

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

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"。我想我可以做一个循环并以这种方式创建哈希,但我应该能够在查询中做到这一点吗?我应该尝试为此使用范围吗?

**更新

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

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

【问题讨论】:

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


    【解决方案1】:

    你想做的查询是

    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

    【讨论】:

    • 很高兴听到这个消息。您应该通过单击左侧的勾号来接受答案...
    猜你喜欢
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多