【问题标题】:Active Record to get children based on condition of parentActive Record 根据父母的情况获取孩子
【发布时间】:2013-01-18 16:21:51
【问题描述】:

我有一个数据库设置:

User has_many :cars
Car  has_many :timeslips
Timeslip  has_one :car

我只需要在父 :car 具有某个 :user_id 时返回 :timeslips

在我的控制器中我想说这样的话:

@timeslips = Timeslip.car.where(:user_id => params[:user_id])

当满足父母条件时,返回所有孩子的最佳做法/方式可能是什么?我应该在模型中做一个方法吗?

【问题讨论】:

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


    【解决方案1】:

    我会使用 ActiveRecord 连接:http://guides.rubyonrails.org/active_record_querying.html#joining-tables

    @timeslips = Timeslip.joins("INNER JOIN cars on timeslips.car_id = cars.id").where("cars.user_id = ?", params[:user_id])
    

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2013-06-04
      • 1970-01-01
      相关资源
      最近更新 更多