【问题标题】:Assigning a category to a product via has_many :through通过 has_many 将类别分配给产品:通过
【发布时间】:2013-03-17 01:46:09
【问题描述】:

允许用户将类别分配给他/他创建的产品的最佳方式是什么?现在,我通过中间分类模型连接了产品和类别模型。

product.rb

class Product < ActiveRecord::Base
  attr_accessible :description, :name

  has_many :categorizations
  has_many :categories, :through => :categorizations
end

category.rb

class Category < ActiveRecord::Base
  attr_accessible :name

  has_many :categorizations
  has_many :products, :through => :categorizations
end

categorization.rb

class Categorization < ActiveRecord::Base
  attr_accessible :category_id, :product_id  # Should I leave these accessible?

  belongs_to :product
  belongs_to :category
end

我最终试图让它在终端中工作:

> product = Product.create(name: "Product A", description: "Product A description")
> Category.create(name: "Cat A")
> product.categories
> []
> product.categories = "Cat A"

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您正在创建一个名称为“Cat A”的类别,但随后您将字符串“Cat A”分配给 product.categories

    试试这个:

    product.categories.create(:name => "Cat A")
    

    【讨论】:

      猜你喜欢
      • 2013-04-20
      • 2014-09-13
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多