如何在rails 5中为has_many关系创建范围?

问题描述 投票:1回答:3

我有一个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
3个回答
3
投票

会像这样参加比赛。

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

3
投票

你可以放入Event.rb

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

你可以打电话给它

@public_events = Group.first.events.public_events

1
投票

你可以用它来做。

scope :public_events, ->(parameter_if_any) {
  where({ private: parameter_if_any||false } )
}
© www.soinside.com 2019 - 2024. All rights reserved.