我想根據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)}' –