【发布时间】:2014-01-30 07:46:35
【问题描述】:
我有三个表:product (id, name)image (id, src)product_images (product_id, image_id, position)
位置字段是产品图像的序号。
Product_images 是连接表。
Rails 4 中也有三种模型:
class Product < ActiveRecord::Base
has_many :product_images, class_name: "ProductImage"
has_many :images, through: :product_images
end
class Image < ActiveRecord::Base
has_many :product_images
has_many :products, through: :product_images, foreign_key: :product_id
accepts_nested_attributes_for :product_images, allow_destroy: true
end
class ProductImage < ActiveRecord::Base
self.table_name = "product_images"
belongs_to :product
belongs_to :image
#has_many :images
#accepts_nested_attributes_for :image, :allow_destroy => true
#attr_accessible :position
end
在控制器中:
def test
@pr = Product.new name: "Super Sofa"
@imgs = Image.find(19, 20)
@imgs[0].position = 1
@imgs[1].position = 2
@pr.images = @imgs
@pr.save
end
Rails 返回此错误: #Image:0x68696e8 的未定义方法 `position='
如何通过Image 模型将位置字段设置为product_images 表?是否可以?也许我对accepts_nested_attributes_of的理解有误。
在这种情况下,纯SQL可能是更好的方法吗?
谢谢。
【问题讨论】:
标签: ruby-on-rails ruby activerecord ruby-on-rails-4