0

所以我有一个资产模型,它被图像和文件作为 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
4

1 回答 1

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
于 2013-02-04T14:16:32.993 回答