2013-07-15 106 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) 

这样,你跟着瘦控制器胖模式“建议”。你的控制器将保持不动。