0

그래서 이미지 및 파일에서 STI로 상속되는 자산 모델이 있습니다. 제품에는 자산으로 많은 이미지가 있습니다. 이 다형성 연결은 잘 작동하지만 모든 자산에 user_id를 추가하는 방법을 알 수 없습니다. 애셋은 이미지 또는 파일과 상관없이 항상 사용자에게 속합니다. 아래 내 코드를 살펴보십시오. 저는 컨트롤러에서 메소드를 작성해야 할 필요가있는 것이 확실하지만 무엇이 확실하지 않습니까? 병합을 시도했습니다 : user_id하지만 콘솔 로그를 볼 때 nil 만 반환합니다. 이상적으로 내가 무엇도 할 싶은 것은 당신이 더 나은에 좋겠, 사용자가 업로드 또는 user.filesSTI & Polymorphic association & user_id

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

코드의 문제점은 무엇입니까? 오류 또는 예외가 발생합니까? 'image.user_id = current_user.id'가 작동하지 않습니까? – KULKING

+0

오류가 발생하지 않습니다. 저장하면 모든 것이 작동하지만 user_id 아래의 에셋 테이블에는 'null'이 표시되고 콘솔 로그에는 에셋에 대한 MySQL 삽입이 'user_id = nil'로 표시됩니다. 아니요'image.user_id = current_user.id'는 nil로 보여지는 것처럼 작동하지 않습니다. – Peter

+0

'image.merge! (: user_id => 1)'로 바꾸고 params를 래핑하기 전에 배치하십시오. :)하지만 다음 대답을보세요 –

답변

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 

@ 한 모든 이미지를 표시합니다 user.images @입니다 상속 논리를 모델로 대체하십시오.

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 
+0

감사의 발레리 당신의'before_save' 정말 잘 작동합니다. 그게 실제로 무엇을 설명 할 수 있습니까? 어떤 링크에서 배울 수 있습니까? – Peter

+0

개체를 저장하기 전에 실행할 콜백을 만듭니다. Look API를 http://api.rubyonrails.org (ActiveRecord :: 콜백) –

+0

죄송합니다,'self.user = assetable.try (: user)'줄을 의미합니다 – Peter