2013-02-25 134 views
1

我在數據庫,products和shopping_list中創建了兩個表。我已經爲產品提供了一個shopping_list的外鍵引用,即product.shopping_list_id。在Rails 3.2中實現count時出錯

我試圖找到在軌道上的紅寶石購物清單中存在的總產品,但我收到一個錯誤。

我給出了一個輸入值的文本框,該值作爲總項存儲在數據庫中。

但是當我在數據庫中添加新產品時,數量沒有在數據庫中得到更新。

我和shopping_list表如下: -

CREATE TABLE shopping_lists 
(
    id serial NOT NULL, 
    shopping_list_name character varying(255), 
    shopping_list_status character varying(255) DEFAULT 'OPEN'::character varying, 
    total_items character varying(255) DEFAULT 0, 
    created_at timestamp without time zone NOT NULL, 
    updated_at timestamp without time zone NOT NULL, 
    deleted integer NOT NULL DEFAULT 0, 
    CONSTRAINT shopping_lists_pkey PRIMARY KEY (id) 
) 

我的產品表如下: -

CREATE TABLE products 
(
    id serial NOT NULL, 
    shopping_list_id integer NOT NULL, 
    product_name character varying(255) DEFAULT 'null'::character varying, 
    product_category character varying(255), 
    quantity integer, 
    status character varying(255) DEFAULT 'OPEN'::character varying, 
    deleted integer NOT NULL DEFAULT 0, 
    CONSTRAINT products_pkey PRIMARY KEY (id) 
) 

我的HTML中,我進入我的值是這個文件即列表: -

<head> 
    <%= javascript_include_tag :application %> 
    <%= csrf_meta_tag %> 
</head> 
<% if @shopping_lists.blank? %> 
    <p>There are no shopping_lists currently in the system.</p> 
<% else %> 
    <p>These are the shopping_lists in the system</p> 
    <table border="1"> 
    <tr><td>shopping_list No.</td><td>shopping_list Name</td><td>status</td><td>quantity</td><td>Edit</td><td>Delete</td></tr> 
    <% @shopping_lists.each do |c| %> 
    <tr> 
    <td><%= link_to c.id, {:action => 'get_product', :id => c.id} %> &nbsp;</td> 
    <td><%= c.shopping_list_name %>&nbsp;</td> 
    <td><%= c.shopping_list_status %>&nbsp;</td> 
    <td><%= c.total_items %>&nbsp;</td> 
    <td><%= link_to 'Edit', {:action => 'edit', :id => c.id} %> &nbsp;</td> 
    <td><%= link_to 'Delete', {:action => 'delete', :id => c.id}, 
    :data => { :confirm => "Are you sure you want to delete this shopping_list?" } %></td> 
    </tr> 
    <% end %> 
    </table> 
<% end %> 
<p><%= link_to "Add new shopping_list", {:action => 'new' }%></p> 

總之我想執行以下查詢: -

Select count(*) from products where shopping_list_id = ''; 

能否請你幫我

回答

3

如果你真的想這樣:

Select count(*) from products where shopping_list_id = ''; 

你可以這樣做:

Product.count(:conditions => "shopping_list_id is NULL") 
+1

使用'.size'更好;如果'Product'集合已經存在,它將不會對數據庫運行第二個查詢。 – deefour 2013-02-25 13:20:28

+1

@ kaeros我在購物清單中實施了這個功能。你能告訴我在哪裏做出更改 – Rockking 2013-02-25 13:21:02

+0

@Deefour更新了我的回答,我認爲這樣會更好。你怎麼看? – Kaeros 2013-02-25 13:21:32

相關問題