我想根据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为上的精选项目的所有国家范围也将返回错误。
你能后的错误讯息呢? –
我不认为你需要在这个范围内的发现 - '范围:by_country, - >(country){joins(:story).where(:stories => {:country_id => country})}'应该为id或国家实例 – Swards
我认为它的后面滴答...试试这个。 '范围:by_country, - >(country){joins(:story).where('stories.country_id =?',country.id)} scope:for_all_countries, - > {joins(:story).where('stories .all_countries =?',true)}' –