【问题标题】:How to scope a join table?如何确定连接表的范围?
【发布时间】:2016-01-21 03:29:07
【问题描述】:

我正在使用filterrific gem,需要确定以下范围。

我有 3 张桌子。而且我想限定用户模型,它返回所有大学名称。所有用户都属于大学。 Colleges 是这里的连接表。我的模型如下(Rails 4.2):

    class User < ActiveRecord::Base
     has_many :colleges
     has_many :universities, :through => colleges

     # my current scope which is not working at all
     scope :user_university, -> (user_university){joins(colleges: [ {university: :name}]).where("universities.name = ? ", user_university)}
    end

    class Colleges < ActiveRecord::Base
     belongs_to :user
     belongs_to :university
    end

    class University < ActiveRecord::Base
     has_many :colleges
     has_many :users, :through => colleges
    end

我不断收到错误,我不确定如何通过连接表确定模型的范围。

【问题讨论】:

    标签: ruby-on-rails scope backend filterrific


    【解决方案1】:

    让我们试试:

    scope :user_university, -> (university_name) {
      joins(colleges: :university).where(universities: {name: university_name})
    }
    

    我将参数user_university 重命名为university_name 顺便说一句,user_university 有点混乱!

    【讨论】:

    • 成功了!!太感谢了!好的会重命名的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2021-07-20
    • 2018-02-10
    • 1970-01-01
    • 2022-11-02
    • 2014-12-04
    相关资源
    最近更新 更多