【问题标题】:How to present a list in views for this如何为此在视图中显示列表
【发布时间】:2016-06-19 13:42:24
【问题描述】:

我想根据用户属性展示产品。所以基本上我是根据用户属性从产品类中检索一个对象。我不知道如何在我的视图中为这些创建一个列表。如何按属性呈现它们?以下是我现在展示所有产品的视图:

<% @products.each do |product| %>
      <%= render "product_row", product: product, order_item: @order_item %>
    <% end %>

我的用户.rb

def products_for_gender
    if gender == 'male'
      Product.where("product_id: '9'")
    elsif gender == 'female'
      Product.where("product_id: '10'")
    else
      Product.where("product_id: '11'")
    end
  end

还有我的控制器:

def index
    @products = Product.all
    @products = current_user.products_for_gender
    @order_item = current_order.order_items.new
  end

现在我在尝试访问产品视图时遇到此错误:

ActiveRecord::StatementInvalid in Products#index
Showing /home/ubuntu/workspace/app/views/products/index.html.erb where line #31 raised:

SQLite3::SQLException: unrecognized token: ":": SELECT "products".* FROM "products" WHERE "products"."active" = ? AND (product_id: '9')

【问题讨论】:

    标签: ruby-on-rails model-view-controller views


    【解决方案1】:

    您的.where() 查询中有语法错误:

    Product.where("product_id: '9'")
    

    这应该是:

    Product.where("product_id = 9")
    # or even better:
    Product.where(product_id: 9)
    

    更新:(每个作者 cmets)

    Product.where(id: 9)
    # or, if you want to make sure the products exist
    Product.find(9)
    

    【讨论】:

    • 第 31 行仍然出现同样的错误:
    • 你修复了所有的where() 查询吗?
    • 是的,我有.. 实际上这不是同一个错误,现在我在尝试查看产品视图时收到此错误:ActiveRecord::StatementInvalid in Products#index Showing /home/ubuntu/workspace/app/ views/products/index.html.erb 其中第 31 行引发:SQLite3::SQLException:没有这样的列:products.product_id: SELECT "products".* FROM "products" WHERE "products"."active" = ? AND "产品"."product_id" = 9
    • 我猜你想通过id 找到产品。我会更新我的答案。
    • 嗯,现在我在第 31 行收到了一个新的错误 undefined method "each":
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2013-12-18
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多