范围有两种不同的条件

时间:2015-11-03 05:29:59

标签: ruby-on-rails model scope backend

我想基于两种不同的条件过滤我的索引上的故事,其中一个是针对当前国家,另一个是针对所有国家/地区。是否有可能创建一个可以为这种情况获取故事的范围?

所有国家/地区都是布尔字段,位于我的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特色项目上所有国家/地区的范围也会返回错误。

2 个答案:

答案 0 :(得分:3)

你可以这样做:

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

您可能需要添加一些逻辑来处理坏参数。

对于联接表,您可以加入并过滤故事。

class FeaturedItem < ActiveRecord::Base

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

end

答案 1 :(得分: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