ActiveRecord::HasManyThroughNestedAssociationsAreR

2019-04-10 15:40发布

I just upgraded to Rails 3.2.10 and am getting an error message that I never used to get when updating a record via RailsAdmin.

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

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

This is my Vendor model:

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

This is my Category model:

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

This is my Product model:

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

This is my CategoryProduct model:

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

2条回答
倾城 Initia
2楼-- · 2019-04-10 15:59

This happens because your association is nested, meaning (from rails source) : A through association is nested if there would be more than one join table... which is your case here.

Apparently a workaround (I didn't test) is telling Vendor it doesn’t need to autosave the association.

has_many :categories, :through => :products, :autosave => false
查看更多
成全新的幸福
3楼-- · 2019-04-10 16:03

You can mark the association as readonly and rails_admin will then not generate the category fields in the form for vendor:

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

查看更多
登录 后发表回答