2013-07-15 35 views
1

我有照片和產品模型。Rails解析後端數據

在創建產品控制器的操作中,我想查找所有未關聯的照片並將它們連接到當前產品。我試圖找到屬於當前用戶的所有照片,哪些產品ID是零。

然後每張照片我會集產品ID爲@ product.id

我應該怎麼辦?

def create 
    @product = current_user.products.create(params[:product]) 
    if @product.save 
     render "show", notice: "Product created!" 

     # code here 

    else 
     render "new", error: "Error submitting product" 
    end 
    end 

    def current_user 
    @current_user ||= User.find_by_auth_token(cookies[:auth_token]) 
    end 

schema.rb

create_table "photos", :force => true do |t| 
    t.integer "product_id" 
    t.integer "user_id" 
    end 

    create_table "products", :force => true do |t| 
    t.string "name" 
    t.integer "user_id" 
    end 

回答

1

首先,你應該使用構建代替創建打造產品的情況下,否則下面的行if @product.save將變得毫無意義。因此,代碼應該是這樣的:

def create 
    @product = current_user.products.build(params[:product]) # using build to construct the instance 
    if @product.save 
    render "show", notice: "Product created!" 

    # Update un-related Photos 
    Photo.where(:product_id => nil).update_all(:product_id => @product.id) 

    else 
    render "new", error: "Error submitting product" 
    end 
end 
+0

它實際上是Photo.where(:product_id => nil,:user_id => current_user).update_all(:product_id => @product.id),但偉大的工作感謝拯救我的生命 –

1

對於組織,你應該Product模型做到這一點:

class Product 

    before_save :set_unassigned_photos 

    def set_unassigned_photos 
    self.photos = user.photos.unassigned 
    end 

Photo型號:

class Photo 

    scope :unassigned, where(product_id: nil) 

這樣,你跟着瘦控制器胖模式「建議」。你的控制器將保持不動。