Я использую postgreSQL. Нужна возможность получать последние шутки с punchlines_count. Я уже добился этого со своим прицелом.Что мне нужно знать, так это то, что мой счетчик punchline не должен включать punchlines, у которых warn_level> 1. Модель Warn имеет punchline_id и weight, weight == warn_level. Пожалуйста, помогите мне составить этот запрос. Уточнения: предупреждение может быть с весом 1 или 2 или может содержать 2 предупреждения с весом 1 каждое. Если warn_level> 1, я не должен учитывать это в своей области. Спасибо!
Мои модели.
class Joke < ActiveRecord::Base
COLUMNS = self.column_names.map{|c| "jokes.#{c}" }.join(', ')
has_many :punchlines, :dependent => :destroy
scope :recent, :order => 'jokes.created_at DESC'
scope :recent_jokes_with_punchline_counter, lambda { |limit|
select("#{Joke::COLUMNS}, COUNT(punchlines.id) as punchlines_count").
joins(:punchlines).
group(Joke::COLUMNS).limit(limit) }
end
class Punchline < ActiveRecord::Base
belongs_to :joke
belongs_to :user
has_many :warns
end
class Warn < ActiveRecord::Base
belongs_to :punchline
belongs_to :user
end
Схема:
create_table "jokes", :force => true do |t|
t.text "content"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "up_votes", :default => 0, :null => false
t.integer "down_votes", :default => 0, :null => false
t.string "cached_slug"
t.integer "popularity"
t.boolean "anonymous", :default => false
t.string "shorten_url"
end
create_table "punchlines", :force => true do |t|
t.text "content"
t.integer "user_id"
t.integer "joke_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "up_votes", :default => 0, :null => false
t.integer "down_votes", :default => 0, :null => false
t.string "cached_slug"
t.boolean "anonymous", :default => false
end
create_table "warns", :force => true do |t|
t.integer "punchline_id"
t.integer "user_id"
t.integer "weight"
end
end