【问题标题】:Rails where condition on has_and_belongs_to_many association在 has_and_belongs_to_many 关联条件下的 Rails
【发布时间】:2016-11-14 13:18:20
【问题描述】:

我在产品和供应商之间有一个has_and_belongs_to_many 关联。

连接表是products_suppliers

我正在尝试在表单中创建依赖选择,以便当我选择供应商时,在产品下拉列表中仅显示相应的产品。

我对 where 条件有疑问。

如果我处于产品属于供应商的情况,我会这样做:

 @products = Product.where("supplier_id = ?", params[:supplier_id])

如何在 has_and_belongs_to_many 关联中实现同样的效果?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord model-associations


    【解决方案1】:

    使用此代码:

    supplier = Supplier.find_by(supplier_id: params[:supplier_id])
    @products =supplier.products if supplier.present?
    

    【讨论】:

      【解决方案2】:

      由于您有 has_and_belongs_to_many 关联,您可以在 Supplier 实例上调用 .products

      这应该可以解决问题

      @products = Supplier.find(params[:supplier_id]).products
      

      【讨论】:

      • 我收到了Couldn't find Supplier with 'id'=,而我之前遇到了另一个错误,所以我猜你的解决方案可以解决问题。我猜该错误与我的代码中的其他内容有关,在接受答案之前我会仔细研究它。
      • @Catmal 听起来像 params[:supplier_id] 正在返回 nil
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多