0

我正在尝试在两个产品之间创建一个简单的商品关联。我遵循了一些教程并认为我做对了,但是每当我尝试直接添加关联项目时,它都会不断抛出错误。我是 ROR 的新手,有人可以帮我理解我在这里做错了什么吗?

class Product < ActiveRecord::Base
  attr_accessible :assoc_product,:product_id, :merch_associations, :aux_description,    :buyable, :long_description, :thumb_url, :full_url, :name, :on_special, :part_number,  :release_date, :short_description, :withdraw_date, :occasion
  has_and_belongs_to_many :categories
  has_many :merch_associations
  has_many :assoc_products, :through => :merch_associations



searchable do
text :aux_description, :long_description, :name, :on_special, :part_number, :short_description
text :categories do 
  categories.map { |category| category.name }
end

        text :occasion

        string :categories, :multiple => true do
        categories.map {|category| category.name }
    end
    string :occasion
    time :release_date

  end
end

class MerchAssociation < ActiveRecord::Base
  attr_accessible :assoc_product, :product_id  
  belongs_to :product
  belongs_to :assoc_product, :class_name => "Product"
end

然后在rails控制台中:

Product.find(1).assoc_products.create(Product.last, :association_type => 'up_sell')
Product Load (0.3ms)  SELECT `products`.* FROM `products` WHERE `products`.`id` = 1 LIMIT 1
Product Load (0.3ms)  SELECT `products`.* FROM `products` ORDER BY `products`.`id` DESC LIMIT 1
(0.0ms)  BEGIN
(0.1ms)  ROLLBACK
NoMethodError: undefined method `stringify_keys' for #<Product:0x007fc20d1ffd70>....
4

1 回答 1

0

您不能通过创建将对象添加到关系中,create方法是使用提供的属性创建新对象。在这里阅读:未定义的方法“stringify_keys!” 铁轨上的红宝石

改为使用Product.find(1).assoc_product << Product.last

association_type您的示例中的参数是什么?我猜您想添加具有属性的相关对象MerchAssocation?如果是这样写:

Product.find(1).merch_associations.create(:assoc_product=>Product.last,:association_type => 'up_sell')
于 2012-07-20T22:30:41.567 回答