ruby-on-rails – 使用上下文在Rails中链接范围
我有4个模特:艺术家,版本,活动& EventItems.
>版本有很多活动 在艺术家我发表了一个范围 我将活动定义为一个艺术家,他正处于一个非选秀状态的活动中. 范围:已发布,– > {joins(:events).where(“events.state!=?”,“draft”).uniq} 这种方法很好,直到我开始链接它们并希望艺术家至少参与为特定版本发布的事件. Edition.first.artists.published 除了它还将加入当前版本之外的事件并错误地发布艺术家(如果他们有任何已发布的事件(即使它们不在此特定版本中))之外,这也是有效的. 为了让它正常工作,我必须像这样破解它(这太可怕了): scope :published,->(edition = nil) { if edition.present? joins(:events).where("events.state != ? AND events.edition_id = ?",'draft',edition.id).uniq else joins(:events).where("events.state != ?",'draft').uniq end } Edition.first.artists.published(Edition.first) 反正有没有提供更多的范围,只包括这个版本中的事件?它的范围是否正确? 谢谢! 解决方法
恕我直言,问题依赖于你的关联和你正在生成的SQL,而不是你应该如何为范围提供上下文(传递参数是完全合法的).
在调用Event.artists时,您已经加入了与has_many:艺术家的活动,通过:: events和不加选择地加入事件.最重要的是,你依靠事件来确定艺术家是否活跃,如果不是SRP违规,这是另一个混??乱的来源. 我认为解决方案来自于定义正确的关联: class Edition has_many :events has_many :artists,through: :events has_many :active_events,-> {where.not(state: "draft")},class_name: "Events" has_many :active_artists,through: :active_events,class_name: "Artist",source: :artists # => not sure if this option is necessary end class Events has_many :event_items has_many :artists,through: :event_items end Event.first.active_artists 我不是100%确定宏选项,但你明白了. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |