【问题标题】:Rails 3 ActiveRecord: Find model by finding it's associationRails 3 ActiveRecord:通过查找模型的关联来查找模型
【发布时间】:2011-05-03 12:11:57
【问题描述】:
class OrderItem belongs_to Item and belongs_to Order

class Item has_many OrderItems and belongs_to ItemType

class ItemType has_many Items

class Order has_many OrderItems

我想在 Order 中查找 Item 类型为 ItemType 的所有 OrderItems

def get_by_item_type(id)
  order_items.where(:item => {:item_type_id => 3})

显然,我可以通过查找所有 OrderItem、循环、测试和构建我自己的集合来做到这一点。没问题,不知道有没有别的办法?

谢谢 /j

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    这将通过以下方式完成:

    def get_by_item_type(id)
      order_items.joins(:item).where(:item_type_id => id)
    end
    

    如果您收到有关不存在/不明确的列的错误,请查看

    order_items.joins(:items).to_sql
    

    为了找到正确的列名。

    【讨论】:

    • 谢谢,我会尽快尝试一下,因为它看起来不错...谢谢
    • 终于实现了系统的这一部分,并且像一个魅力一样工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多