简体   繁体   English

STI&多态关联和user_id

[英]STI & Polymorphic association & user_id

So I have an assets model which is inherited by images and files as STI. 因此,我有一个资产模型,该模型由图像和文件作为STI继承。 Products has many images as assetable. 产品具有许多可获利的图像。 This polymorphic association is working fine but I can't figure out how to add the user_id to every asset. 这种多态关联工作正常,但我不知道如何将user_id添加到每个资产。 A asset always belongs to a user no matter if its an image or file. 资产始终属于用户,无论其是图像还是文件。 Please look at my code below. 请在下面查看我的代码。 I'm pretty sure there's something I need to do within the controllers create method but I'm not sure what? 我很确定在控制器的create方法中我需要做些什么,但是我不确定是什么? I've tried merging :user_id but this just returns nil when looking at the console log. 我尝试合并:user_id,但是在查看控制台日志时,它只会返回nil。 Ideally what I'd also like to do is @user.images which will display all the images that the user has uploaded or even @user.files 理想情况下,我还要执行的操作是@ 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
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

By the way, you'd better to replace inheritance logic into the model: 顺便说一句,您最好将继承逻辑替换为模型:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM