Skip to content

Commit ce5261a

Browse files
committed
Only show top level categories on the categories index page
1 parent 75fee9c commit ce5261a

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

src/category.rs

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,18 @@ impl Category {
115115

116116
Ok(invalid_categories)
117117
}
118+
119+
pub fn count_toplevel(conn: &GenericConnection) -> CargoResult<i64> {
120+
let sql = format!("\
121+
SELECT COUNT(*) \
122+
FROM {} \
123+
WHERE category NOT LIKE '%::%'",
124+
Model::table_name(None::<Self>
125+
));
126+
let stmt = try!(conn.prepare(&sql));
127+
let rows = try!(stmt.query(&[]));
128+
Ok(rows.iter().next().unwrap().get("count"))
129+
}
118130
}
119131

120132
impl Model for Category {
@@ -141,10 +153,13 @@ pub fn index(req: &mut Request) -> CargoResult<Response> {
141153
_ => "ORDER BY category ASC",
142154
};
143155

144-
// Collect all the categories
145-
let stmt = try!(conn.prepare(&format!("SELECT * FROM categories {} \
146-
LIMIT $1 OFFSET $2",
147-
sort_sql)));
156+
// Collect all the top-level categories
157+
let stmt = try!(conn.prepare(&format!(
158+
"SELECT * FROM categories \
159+
WHERE category NOT LIKE '%::%' {} \
160+
LIMIT $1 OFFSET $2",
161+
sort_sql
162+
)));
148163

149164
let categories: Vec<_> = try!(stmt.query(&[&limit, &offset]))
150165
.iter()
@@ -155,7 +170,7 @@ pub fn index(req: &mut Request) -> CargoResult<Response> {
155170
.collect();
156171

157172
// Query for the total count of categories
158-
let total = try!(Category::count(conn));
173+
let total = try!(Category::count_toplevel(conn));
159174

160175
#[derive(RustcEncodable)]
161176
struct R { categories: Vec<EncodableCategory>, meta: Meta }

src/tests/category.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,21 @@ struct GoodCategory { category: EncodableCategory }
1616
fn index() {
1717
let (_b, app, middle) = ::app();
1818
let mut req = ::req(app, Method::Get, "/api/v1/categories");
19+
20+
// List 0 categories if none exist
1921
let mut response = ok_resp!(middle.call(&mut req));
2022
let json: CategoryList = ::json(&mut response);
2123
assert_eq!(json.categories.len(), 0);
2224
assert_eq!(json.meta.total, 0);
2325

26+
// Create a category and a subcategory
2427
::mock_category(&mut req, "foo", "foo");
28+
::mock_category(&mut req, "foo::bar", "foo::bar");
29+
2530
let mut response = ok_resp!(middle.call(&mut req));
2631
let json: CategoryList = ::json(&mut response);
32+
33+
// Only the top-level categories should be on the page
2734
assert_eq!(json.categories.len(), 1);
2835
assert_eq!(json.meta.total, 1);
2936
assert_eq!(json.categories[0].category, "foo");

0 commit comments

Comments
 (0)