所以我有一个资产模型,它由图像和文件作为STI继承。产品有许多图像可以解决。这种多态关联工作正常,但我无法弄清楚如何将user_id添加到每个资产。无论资产是图像还是文件,资产始终属于用户。请看下面的代码。我很确定在控制器创建方法中我需要做些什么,但我不确定是什么?我尝试过合并:user_id但是这只是在查看控制台日志时返回nil。理想情况下,我还想做的是@ user.images,它将显示用户上传的所有图像,甚至是@ user.files
class User < ActiveRecord::Base
has_many :products
has_many :assets
end
class Asset < ActiveRecord::Base
belongs_to :assetable, :polymorphic => true
belongs_to :user
end
class Image < Asset
mount_uploader :filename, ImageUploader
attr_accessible :filename, :assets
end
class Product < ActiveRecord::Base
belongs_to :user
has_many :images, as: :assetable
accepts_nested_attributes_for :images
attr_accessible :name, :price, :images_attributes
validates_presence_of :name
end
class ProductsController < ApplicationController
def create
@product = Product.new(params[:product])
@product.user_id = current_user.id
params[:product][:images_attributes].each do |key, image|
# image.user_id = current_user.id
image.merge(:user_id => 1)
end
@product.save
end
end
答案 0 :(得分:0)
def create
params[:product][:images_attributes].each do |key, image|
image.merge!(:user_id => current_user.id)
end
@product = Product.new(params[:product])
@product.user_id = current_user.id
@product.save
end
顺便说一句,你最好将继承逻辑替换为模型:
class Image < Asset
mount_uploader :filename, ImageUploader
attr_accessible :filename, :assets
before_save do
self.user = assetable.try(:user)
end
end
# controller
def create
@product = Product.new(params[:product])
@product.user = current_user
@product.save
end