【问题标题】:How to add associations to models in rails如何在 Rails 中为模型添加关联
【发布时间】:2023-03-25 11:15:02
【问题描述】:

我有三个模型

class SupplierVariant

  belongs_to  :supplier
  belongs_to  :variant

end

class Supplier

  has_many :variants, :through :supplier_variants

end

class Variant

end

现在我想知道,如何获得特定变体的供应商。我添加了一个关联 has_one :supplier through: :supplier_variant 在 Variant 类中

但是当我执行以下查询时,我得到下面提到的错误

p=Spree::Variant.find(384)

  Spree::Variant Load (1.2ms)  SELECT  "spree_variants".* FROM "spree_variants" WHERE "spree_variants"."deleted_at" IS NULL AND "spree_variants"."id" = ? LIMIT 1  [["id", 384]]
 => #<Spree::Variant id: 384, sku: "CHG137-Blue-XL", weight: #<BigDecimal:a396b38,'0.5E3',9(27)>, height: #<BigDecimal:a396a20,'0.5E2',9(27)>, width: #<BigDecimal:a3968e0,'0.45E2',9(27)>, depth: #<BigDecimal:a396778,'0.75E2',9(27)>, deleted_at: nil, is_master: false, product_id: 228, cost_price: #<BigDecimal:a3962c8,'0.9E3',9(27)>, position: 4, cost_currency: "INR", track_inventory: true, tax_category_id: 3, updated_at: "2015-05-25 05:58:19", stock_items_count: 4> 

p.supplier
**NoMethodError: undefined method `supplier' for #<Spree::Variant:0x0000000a3973a8>**

如何在 Rails 的模型文件夹中添加正确的关联?以及添加后如何使用? 在表之间应用连接操作是否取决于我们在模型中定义的关联?

【问题讨论】:

    标签: ruby database ruby-on-rails-3 ruby-on-rails-4 spree


    【解决方案1】:
    class SupplierVariant
    
      belongs_to  :supplier
      belongs_to  :variant
    
    end
    
    class Supplier
      has_many :supplier_variants
      has_many :variants, :through :supplier_variants
    
    end
    
    class Variant
      has_many :supplier_variants
      has_many :suppliers, :through :supplier_variants
    end
    

    更正这些模型的关联。

    @variant = Variant.last
    @suppliers = @variant.suppliers
    

    它将为您提供特定变体的供应商。

    【讨论】:

      【解决方案2】:

      您需要将适当的关联添加到您的 Variant 类,例如has_many :suppliers, :through :supplier_variants。现在它只是一个没有方法的空类,因此出现未定义方法错误。

      【讨论】:

      • 感谢@Michael 的回答。表之间的连接是否取决于我们在模型中定义的关联?为什么当我添加关联 has_one :supplier, :through :supplier_variant 时它不起作用?
      • @Shakthi 您必须在两个方向上声明关联。您的供应商知道您的变体,但您的变体一无所知。这正是 Rails 的方式。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-19
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2023-01-21
      • 1970-01-01
      相关资源
      最近更新 更多