2015-11-03 56 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