【发布时间】:2016-02-03 04:25:47
【问题描述】:
我想根据 2 种不同的条件过滤我的索引中的故事,其中一种适用于当前国家,另一种适用于所有国家。是否有可能创建一个可以为这两种情况获取故事的范围?
所有国家都是布尔字段,在我的 Story 表中。逻辑是如果为所有国家/地区创建故事,则字段 all_countries = 1
特色项目模型,如果作者愿意,故事可以在索引页面上显示。
这就是我的模型现在使用范围的样子
class Country < ActiveRecord::Base
has_many :stories
end
class Story < ActiveRecord::Base
belongs_to :countries
has_many :featured_items, dependent: :destroy
scope :by_country, lambda { |id| where(:country_id => id)}
scope :for_all_countries, where(:all_countries => true)
end
class FeaturedItem < ActiveRecord::Base
belongs_to :story
scope :by_country, -> (country) {joins(:story).where('`stories`.country_id = ?', Country.find(country) )}
scope :for_all_countries, -> { joins(:story).where('`stories`.all_countries = ?',true) }
end
p/s 特色项目上所有国家/地区的范围也会返回错误。
【问题讨论】:
-
你能把错误信息也贴出来吗?
-
我认为您不需要在此查找 -
scope :by_country, -> (country) { joins(:story).where(:stories => { :country_id => country } ) }应该适用于 id 或国家/地区实例 -
我认为它的倒钩...试试这个。
scope :by_country, -> (country) {joins(:story).where('stories.country_id = ?', country.id )} scope :for_all_countries, -> { joins(:story).where('stories.all_countries = ?',true) } -
但我仍然会返回 2 个不同的范围。我想知道我是否可以创建一个范围,其中的故事适用于 current_country 的条件,它意味着适用于 current_country 和所有国家/地区。
标签: ruby-on-rails model scope backend