4

我有以下问题,我的客户账单视图中有以下问题

<%= f.collection_select :product_id,Product.all,:id,:name %>

这是从“产品”模型中获取所有产品的列表,并提供从中选择的选项。但我想从“StoreOpeningStock”模型中选择产品列表。

我的模型中有这些

class Product< ActiveRecord::Base
has_many :store_opening_stocks
has_many :customer_bills
attr_accessible :name
end


class StoreOpeningStock < ActiveRecord::Base
attr_accessible :product_id
belongs_to :product 
end


class CustomerBill < ActiveRecord::Base
attr_accessible :product_id
 belongs_to :product
accepts_nested_attributes_for :store_opening_stock
end

谁能指导我如何从 store_opening_stock 获取产品名称和 id ???我应该使用助手吗???还是有其他方法??提前致谢

我尝试使用助手

def getting_prod_names
        @sto = StoreOpeningStock.all

          for x in @sto
        [
            ['{x.product.title}', '{x.product_id}']
        ]
    end
    end

获得以下输出

<%= f.select :product_id, options_for_select(getting_prod_names) %>

在此处输入图像描述

任何帮助?:)

4

4 回答 4

3

当您创建表单时,用于创建表单的数据collection_select不限于您要为其创建对象的类。您可以简单地执行以下操作:

<%= f.collection_select :product_id,StoreOpeningStock.all,:product_id ,:name %>

这应该给你,...

将此添加到您的StoreOpeningStock课程中:

def name
    return self.product.name unless self.product.nil?
    ""
end
于 2012-06-22T11:22:33.790 回答
3

你需要澄清你的模型之间的关系......

但只是给你一个想法。您可以在与视图相关的controller内部(显示集合的位置)定义要在 中显示的产品集合。action

控制器:

@products= #here you should call all products you want

然后,您的产品集合可以显示如下:

<%= f.collection_select :product_id, @products,:id,:name %>

编辑

您需要修改模型之间的关系。Aproduct有很多customer_bills,但你确定每个都customer_bill属于一个product吗?
我认为你有一个多对多的关系,因为 acustomer_bill也可以有很多products.
如果我理解正确,解决方案是ProductLine在这种多对多关系之间创建一个模型。

Product另外,和 和有什么区别StoreOpeningStock?您在 中包含了哪些属性StoreOpeningStock
如果您创建此模型只是为了显示产品的可用性,为什么不在Product模型中添加一个属性,例如一个名为availability.

于 2012-06-22T11:53:57.993 回答
1

因此,您想查找所有具有 StoreOpeningStock 的产品。这只是一个模型问题,与助手无关。

class Product
  # Find all products that have a StoreOpeningStock
  def self.in_stock
    find(StoreOpeningStock.product_ids)
  end
end

class StoreOpeningStock
  # Collect all product ids from stocks
  def self.product_ids
    uniq.pluck(:product_id)
  end
end

现在您可以使用 Product.in_stock 而不是 Product.all 来拥有唯一的库存。

于 2012-06-22T12:58:45.653 回答
1

我会为您的产品模型添加一个范围:

class Product< ActiveRecord::Base
    has_many :store_opening_stocks
    has_many :customer_bills
    attr_accessible :name

    scope :having_store_opening_stocks, :joins => : store_opening_stocks, :select => 'distinct product.*', :conditions => 'store_opening_stocks.product > 0'
end

然后您可以使用 Product.all.having_store_opening_stocks 仅选择具有此类库存的产品,例如:

<%= f.select :product_id, Product.having_store_opening_stocks.map { |product| [product.name, product.id] } %>
于 2012-06-22T15:58:40.870 回答