【发布时间】:2011-10-21 17:39:15
【问题描述】:
我正在使用 postgreSQL。需要使用punchlines_count 获取最近的笑话的范围。我已经用我的范围实现了这一点。我需要知道的是我的妙语计数器不应包括具有警告级别 > 1 的妙语。警告模型具有妙语 ID 和重量,重量 == 警告级别。请帮我建立这个查询。 澄清:Punchline 警告可能是权重 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
【问题讨论】:
-
你为什么不分配赏金?这很糟糕......
标签: sql ruby-on-rails ruby-on-rails-3 postgresql activerecord