Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 有很多:通过并获取相关项目_Ruby On Rails_Ruby On Rails 3_Activerecord - Fatal编程技术网

Ruby on rails 有很多:通过并获取相关项目

Ruby on rails 有很多:通过并获取相关项目,ruby-on-rails,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby On Rails 3,Activerecord,这是对这一问题的后续行动 基本上,我希望在我的Invoice类中有一个函数,用于获取所有行项目,但以下功能不起作用: 因此: 根据前一个问题中的关联,这是否有效?我认为如果我直接访问产品,应该: > @p=Product.find(1) # good > @p.line_items # also good 如何取回基于此模型的所有行项目 thx@i.products返回产品集合。您需要收集所有行项目: @i.products.collect

这是对这一问题的后续行动

基本上,我希望在我的Invoice类中有一个函数,用于获取所有行项目,但以下功能不起作用:

因此:

根据前一个问题中的关联,这是否有效?我认为如果我直接访问产品,应该:

> @p=Product.find(1)      # good  
> @p.line_items           # also good
如何取回基于此模型的所有行项目

thx

@i.products返回产品集合。您需要收集所有行项目:

    @i.products.collect(&:line_items)
@i、 产品返回产品的集合。您需要收集所有行项目:

    @i.products.collect(&:line_items)

假设您有以下型号:

class Invoice
  has_many :line_items
  has_many :products, :through => :line_items
end

class LineItems
  belongs_to :invoice
  belongs_to :product
end

class Product
  has_many :line_items
  has_many :invoices, :through => :line_items
end
您可以执行以下操作:

@i=发票。发现1良好 @i、 好的产品很好用 @i、 行项目与发票关联的所有行项目


假设您有以下型号:

class Invoice
  has_many :line_items
  has_many :products, :through => :line_items
end

class LineItems
  belongs_to :invoice
  belongs_to :product
end

class Product
  has_many :line_items
  has_many :invoices, :through => :line_items
end
您可以执行以下操作:

@i=发票。发现1良好 @i、 好的产品很好用 @i、 行项目与发票关联的所有行项目


可能重复的has_many:through允许您获取可从一个模型对象而不是所有模型对象间接访问的所有模型对象。看我对你第一个问题的回答:我认为这个问题没有意义。一旦您解决了问题,请随时重新询问,您可以使用一种称为的方法来选择集合中的集合。可能的“有多个:通过”重复允许您获取从一个模型对象而不是所有模型对象间接访问的所有模型对象。看我对你第一个问题的回答:我认为这个问题没有意义。一旦你解决了问题,请随意再问这个问题,有一个叫做的东西,你可以用来选择集合中的集合。这个应该是@i.products.sum[],&:line\u items这会给你一个数组,最好是:@i.products.sum[],&:line\u items或@i.products.collect&:line\u items.flattle这应该是@i.products.sum[],&:line_items这将为您提供一个数组,最好是:@i.products.sum[],&:line_items或:@i.products.collect&:line_items.flattle这使LineItems成为介于产品和发票之间的类。我试图建立的模型有点古怪,因为每个产品都是独一无二的,所以“行项目”实际上是内部会计的“成本”。我之所以问这个问题,是因为我看到的大多数示例都使用了两个所属的类作为连接类。这使得行项目成为产品和发票之间的类别。我试图建立的模型有点古怪,因为每个产品都是独一无二的,所以“行项目”实际上是内部会计的“成本”。我之所以问这个问题,是因为我看到的大多数示例都使用了两个所属的类作为连接类。谢谢