【问题标题】:How to create a scope for a has_many relationship in rails 5?如何在 Rails 5 中为 has_many 关系创建范围?
【发布时间】:2019-02-15 05:13:30
【问题描述】:

我有一个 Group 模型,其中有许多 Events,我正在尝试仅通过 Group.public_events 之类的方式查找具有公共活动的组

这是我的组:

class Group < ApplicationRecord
  has_many :events, dependent: :destroy
end

这是我的活动:

class Event < ApplicationRecord
  belongs_to :group
end

我想创建一个scope :public_events 以在活动中找到.where(private: false),但这应该在小组或活动中进行吗?

【问题讨论】:

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


    【解决方案1】:

    会像这样参加活动。

    class Event < ApplicationRecord
      belongs_to :group
      scope :public_events, -> { where(private: false) }
    end
    

    【讨论】:

    • 你称它为 Group.first.public_events 吗?因为我得到一个 noMethodError。谢谢
    • 你可以叫它Group.public_events
    • 称之为 Group.public_events
    【解决方案2】:

    你可以放入Event.rb

    class Event < ApplicationRecord
      belongs_to :group
      scope :public_events, lambda { where('private = ?',false)}
    end
    

    你可以这样称呼它

    @public_events = Group.first.events.public_events
    

    【讨论】:

    • 如果我这样做,我会得到一个未定义的方法错误。我究竟做错了什么?谢谢
    • 啊抱歉我忘了提.events,我刚刚在上面更正了@public_events = Group.first.events.public_events
    【解决方案3】:

    你可以这样做。

    scope :public_events, ->(parameter_if_any) {
      where({ private: parameter_if_any||false } )
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 2017-11-11
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 2011-10-05
      • 1970-01-01
      相关资源
      最近更新 更多