请告诉我将记录保存到两个连接表中的优雅方法
我有三张桌子(型号):
id
,name
,sizes
id
,name
,file_path
product_id
,image_id
,position
position
字段表示序号我们走了。
class Product < ActiveRecord::Base
validates :name, :presence => true
validates :description, :presence => true
has_and_belongs_to_many :categories
has_many :product_images
has_many :images, through: :product_images
end
class Image < ActiveRecord::Base
has_many :product_images
has_many :images, through: :product_images
# attr_accessor :position
# def position
# product_images.position
# p "Test Position"
# end
def file_path
"sofas/imgs/" + super
end
end
和联接表:
class ProductImage < ActiveRecord::Base
self.table_name = "images_products"
belongs_to :image
belongs_to :product
end
我期待这样的事情:
pr = Product.new
imgs = Images.find(params[:checked_images][ids])
pr.images = imgs
# It's should not work, I know. But I don't know right way.
pr.images[0].product_image.position = 0
# or something like:
pr.images[0].position = 0
也许有办法通过图像模型映射表“ images_products ”的“位置”字段。好吧,我很困惑。
答案 0 :(得分:1)
回答你的问题。我个人会做一些......
@product.images.build(image_params)
@product.save
在控制器中。