6

我刚刚升级到Rails 3.2.10并收到一条错误消息,这是我在通过 RailsAdmin 更新记录时从未收到过的错误消息。

ActiveRecord::HasManyThroughNestedAssociationsAreReadonly at /admin/vendor/12/edit

Message Cannot modify association 'Vendor#categories' because it goes through more than one other association.

这是我的Vendor模型:

class Vendor < ActiveRecord::Base
  attr_accessible :name, :description, :banner_image, :logo_image, :intro_text, :thumb_image, :category_ids, :product_ids, :user_id, :remove_banner_image, :banner_image_cache, :remove_logo_image, :logo_image_cache
    mount_uploader :banner_image, ImageUploader
    mount_uploader :logo_image, ImageUploader
    mount_uploader :thumb_image, ImageUploader

    has_many :products, :dependent => :destroy
    has_many :categories, :through => :products
    belongs_to :owner, :class_name => "User",
        :foreign_key => "user_id"   
end

这是我的Category模型:

class Category < ActiveRecord::Base
  attr_accessible :name, :product_ids, :category_ids
    has_many :category_products do
         def with_products
           includes(:product)
         end
       end

  has_many :products, :through => :category_products

end

这是我的Product模型:

class Product < ActiveRecord::Base
  attr_accessible :name, :description, :price, :vendor_id, :image, :category_ids, :sku, :remove_image, :image_cache
    mount_uploader :image, ImageUploader

    belongs_to :vendor
    has_many :category_products do
           def with_categories
             includes(:category)
           end
    end

    has_many :categories, :through => :category_products

end

这是我的CategoryProduct模型:

class CategoryProduct < ActiveRecord::Base
  attr_accessible :product_id, :category_id, :purchases_count

    belongs_to :product
  belongs_to :category

  validates_uniqueness_of :product_id, :scope => :category_id
end
4

2 回答 2

0

发生这种情况是因为您的关联是嵌套的,这意味着(来自 rails 源):如果存在多个连接表,则通过关联是嵌套的……这就是您的情况。

显然,一种解决方法(我没有测试)告诉供应商它不需要自动保存关联。

has_many :categories, :through => :products, :autosave => false
于 2013-01-14T09:06:30.057 回答
0

您可以将关联标记为只读,然后 rails_admin 将不会在表单中为供应商生成类别字段:

has_many :categories, -> { readonly }, through: :products

于 2014-08-03T19:15:37.553 回答