Ruby on rails 从Rails中的Activerecord::关系生成记录数组
对Rails来说相当陌生,正在构建一个电子商务系统 我有一个树状结构的产品->库存单位->行项目 其中:Ruby on rails 从Rails中的Activerecord::关系生成记录数组,ruby-on-rails,activerecord,relation,Ruby On Rails,Activerecord,Relation,对Rails来说相当陌生,正在构建一个电子商务系统 我有一个树状结构的产品->库存单位->行项目 其中: class LineItem < ActiveRecord::Base belongs_to :sku belongs_to :cart class Sku < ActiveRecord::Base belongs_to :product class Product < ActiveRecord::Base has_many :skus has_ma
class LineItem < ActiveRecord::Base
belongs_to :sku
belongs_to :cart
class Sku < ActiveRecord::Base
belongs_to :product
class Product < ActiveRecord::Base
has_many :skus
has_many :line_items, :through => :skus
返回行项目的数组
在订购阶段,我需要确定是否有任何行项目需要许可证,如果需要,则显示许可证以供验收
我已尝试链接作用域:
class LineItem < ActiveRecord::Base
scope :license?, joins(:sku) & Sku.license?
class Sku < ActiveRecord::Base
scope :license?, joins(:product) & Product.license?
class Product < ActiveRecord::Base
scope :license?, where(:license => true)
@cart.line_items.license?
它返回一个ActiveRecord::Relation,但是
@cart.line_items.joins(:sku).joins(:product).where(:rct => true).empty?
@cart.line_items.joins(:sku).joins(:product).where(:rct => true).to_a
@cart.line_items.joins(:sku).joins(:product).where(:rct => true).all
在前两种情况下,all都无法给出布尔值(在第一种情况下)或数组
我可以循环:
<% @cart.line_items.each do |item| %>
<h4><%= item %></h4>
<h4><%= item.sku.product.license %></h4>
<% end %>
查看所有正确的布尔值,但必须有更好的方法来实现这一点,而不是在我的顺序视图中使用此循环的变体,或者必须创建一个类方法来循环并生成布尔值
有什么想法吗?似乎该产品能够理解它是否需要许可证。在这种情况下,您需要沿着链从行项目一直到产品获取该信息。您可以在
LineItem
类上添加一个needs\u license?
方法,该方法委托给它的Sku,委托给它的产品,然后过滤掉行项目,如下所示:
class LineItem
def needs_license?
sku.needs_license?
end
end
class Sku
def needs_license?
product.needs_license?
end
end
class Product
def needs_license?
license
end
end
最后,
@cart.line_items.select(&:needs_license?)
多谢!这工作得很完美,这就是我认为我在使用链接作用域时所做的。链接类方法显然做了一些不同的事情。
class LineItem
def needs_license?
sku.needs_license?
end
end
class Sku
def needs_license?
product.needs_license?
end
end
class Product
def needs_license?
license
end
end
@cart.line_items.select(&:needs_license?)