2015-11-03 55 views
2

我想根據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爲上的精選項目的所有國家範圍也將返回錯誤。

+0

你能後的錯誤訊息呢? –

+0

我不認爲你需要在這個範圍內的發現 - '範圍:by_country, - >(country){joins(:story).where(:stories => {:country_id => country})}'應該爲id或國家實例 – Swards

+0

我認爲它的後面滴答...試試這個。 '範圍:by_country, - >(country){joins(:story).where('stories.country_id =?',country.id)} scope:for_all_countries, - > {joins(:story).where('stories .all_countries =?',true)}' –

回答

3

你可以做這樣的事情:

scope :by_country, -> (country) { country == :all ? where(:all_countries => true) : where(:country_id => country) } 

您可能需要添加多一點的邏輯來處理不良PARAMS。

對於連接表,您可以連接並過濾故事。

class FeaturedItem < ActiveRecord::Base 

    scope :by_country, -> (country) { (country == :all ? where(:stories => { :all_countries => true }) : where(:stories => { :country_id => country })).joins(:story) } 

end 
+0

謝謝!它適用於故事模型。但如何回合表格?這是特色項目模型。目前國家的當前範圍是這樣的,我希望代碼也適用於所有國家的範圍:by_country, - >(country){joins(:story).where('stories'.country_id =? ',國家。find(country)}' – Purry

+0

已更新爲FeaturedItem的作用域 – Swards

+0

謝謝,但它會返回故事具有current_country id && all_countries == true的查詢。需要展示的故事是當前國家和所有國家的故事。 – Purry

1

scope語法是目前錯誤的,因爲是你的belongs_to協會的多元化。

你需要使用以下(@swards答案是正確的,這僅僅是一個加法):

#app/models/story.rb 
class Story < ActiveRecord::Base 
    belongs_to :country 
    scope :countries, ->(ids = :all) { ids == :all ? where(all_countries: true) : find(ids) } 
end 

這將允許你打電話Story.countries返回所有國家和Story.countries(1,2,4,5)返回個別。

根據2個不同的條件篩選我的索引中的故事,其中一個針對當前國家,另一個針對所有國家/地區。

你有沒有使用你的Country模型如下考慮:

@stories = @country ? @country.stories : Country.stories 

#app/models/country.rb 
class Country < ActiveRecord::Base 
    has_many :stories 
    scope :stories, -> { joins(:stories).where(story: {all_countries: true}) } 
end 
+0

謝謝,但是這段代碼爲我過濾了當前國家和所有的故事 'scope:by_country, - >(country){joins(:story).where('stories'.country_id =?or' story'.all_countries = 1',country)}' – Purry