【问题标题】:has_many by boolean value in railshas_many 通过rails中的布尔值
【发布时间】:2016-07-18 19:53:16
【问题描述】:

在我的 ruby​​ on rails 应用程序中,我有两个模型:用户和项目

在我的用户模型中,我想要一个用户可以拥有许多这样的项目的关系:

has_many :items

对于关系,我不会只使用 items 表中的 user_id 列。

当我这样做时

User.includes(:items) 

我宁愿拥有所有物品 - 物品 user_id 属于用户(经典方式) - 或者例如布尔列(如 all_users)为真

这个可以用

has_many :items + any special options? 

它会是什么样子?

感谢和问候,安德烈亚斯

【问题讨论】:

    标签: ruby-on-rails ruby model include has-many


    【解决方案1】:

    User.includes(:items) 只是指示 Rails SQL builder 加载所有 嵌套 项与加载的用户。

    也就是说,

    User.includes(:items).all # will load all users with all nested items
    User.includes(:items).where(name: 'Joe') # will load user(s) Joe and their items
    

    这样做是为了尽量减少对数据库的查询量。

    是否要加载所有项目,应使用Item上的查询,例如:

    Item.where(user_id: User.find_by_name('Joe').pluck(:id))
    

    【讨论】:

    • 谢谢,但我正在寻找的是将一个项目与一个或所有用户相关联,而不需要一个 many_to_many 关联,而是一个“all_users”复选框。
    • 我无法读懂你的想法。顺便说一句,这在没有 manytomany 的关系数据库中是不可能的。
    猜你喜欢
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    相关资源
    最近更新 更多