【问题标题】:Filter on empty related field - Rails过滤空的相关字段 - Rails
【发布时间】:2016-03-06 22:46:59
【问题描述】:

问这个问题是因为我没有找到任何可以帮助我解决问题的主题。 背景:Rails 相对较新,构建了一个订单管理系统。为简化起见,我有 3 个模型存在问题:Item、SupplierQuote 和 SupplierQuoteDetail

Item 给出了 Item 的名称、描述和部件号

 class Item < ActiveRecord::Base
   has_many :supplier_quote_details
   has_many :supplier_quotes, through: :supplier_quote_details

SupplierQuote 提供报价参考和报价日期

 class SupplierQuote < ActiveRecord::Base
    has_many :supplier_quote_details
    has_many :items, through: :supplier_quote_details
    accepts_nested_attributes_for :supplier_quote_details, 
    :reject_if => lambda {|x| x[:item_id].blank? }, allow_destroy: true

SupplierQuoteDetail 根据特定报价为商品提供价格

 class SupplierQuoteDetail < ActiveRecord::Base
    belongs_to :item
    belongs_to :supplier_quote

当我输入新的报价时,我有一个嵌套表单(带有字段 for),并且在嵌套的 field_for 中我有一个选择标签,允许我选择一个可以输入价格的项目。但是,在我的选择下拉列表中,我只想要以前没有价格输入的值。所以在我的供应商报价控制器中,我有:

@items = Item.joins(:supplier_quote_details).merge(SupplierQuoteDetail.where(unit_price: nil))

但这给了我一个空的下拉菜单! (不应该,因为我有很多没有价格的物品):

 <%= f.fields_for :supplier_quote_details, :wrapper => false do |it| %>
   <tr class="fields">
     <td><%= it.select(:item_id, @items.map {|item| [[item.description, item.PN, item.SN].join("   |   "), item.id]}) %></td>

请帮忙!如何在这个相关领域正确过滤?以上是我目前发现的唯一方法。

非常感谢!

一个。

【问题讨论】:

  • 尝试使用此调用@items = Item.joins(:supplier_quote_details).merge(SupplierQuoteDetail.where(unit_price: nil)) 的输出查询对其进行调试。这正在形成什么查询?
  • 试试Item.includes(:supplier_quote_details).where( :supplier_quote_details =&gt; { :unit_price =&gt; nil } )
  • 这成功了!非常感谢!
  • 请标记答案正确并关闭它..谢谢

标签: ruby-on-rails postgresql join nested-forms


【解决方案1】:

试试这个:

 Item.includes(:supplier_quote_details).where( :supplier_quote_details => { :unit_price => nil }

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2018-12-30
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多