【问题标题】:Error while implementing count in Rails 3.2在 Rails 3.2 中实现计数时出错
【发布时间】:2013-02-25 12:43:02
【问题描述】:

我在数据库中创建了两个表,products 和 shopping_list。我给产品一个外键引用的 shopping_list 是 product.shopping_list_id。

我正在尝试在 ruby​​ on rails 中查找购物清单中的所有产品,但出现错误。

我已经给了一个文本框来输入值,并且该值作为总数存储在数据库中。

但是当我在数据库中添加新产品时,数据库中的数量没有更新。

我的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 = '';

你能帮帮我吗

【问题讨论】:

    标签: ruby-on-rails database ruby-on-rails-3 html postgresql


    【解决方案1】:

    如果你真的想要这个:

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

    你可以这样做:

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

    【讨论】:

    • 使用.size更好;如果 Product 集合已经存在,它不会对数据库运行第二次查询。
    • @kaeros 我想在购物清单中实现这一点。所以你能告诉我在哪里进行更改
    • @Deefour 更新了我的答案,我认为这读起来更好。你怎么看?
    • @ArseneW @shopping_list.products.size 在你的情况下是c.products.size
    • 我把这个@Kaeros放在哪里
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多