【问题标题】:rails 3 creating an index from two models using where clauserails 3 使用 where 子句从两个模型创建索引
【发布时间】:2012-12-24 05:31:21
【问题描述】:

快速轨道部分,假设我有两个模型用户和角色,我想根据某个角色创建用户的索引/列表,我该如何在我的控制器中构建它

是不是有点像

#first create the association
@user = role.build

#then build the index based on a Role of role_id = 2
@userrole = @user.where(@user.role_id == 2)

我知道这是伪代码,但这是正确的吗?什么是正确的 rails 代码?

【问题讨论】:

    标签: ruby-on-rails-3 model-view-controller controller


    【解决方案1】:
    roles = Role.where(id: [1, 2])
    users = User.where(role_ids: roles.collect(&:ids))
    

    这只是一个示例,因为显然如果我们已经知道 ID,我们就不需要第一个查询,但是如果我们的角色有一个可编辑的列(例如),我们可以这样做:

    roles = Role.where(editable: true)
    users = User.where(role_ids: roles.collect(&:ids))
    

    如果我们想订购这些,我们可以简单地添加:

    users = User.where(role_ids: roles.collect(&:ids)).order("created_at DESC")
    

    【讨论】:

    • 这就是我的工作方式@users = User.includes(:roles).where('roles.id' => 2)
    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 2018-08-16
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多