i have photo , product models.
in create action of product controller want find unassociated photos , connect them current product. trying find photos belong current user product id nil.
then each photo set product id @product.id
what should do?
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 |t| t.integer "product_id" t.integer "user_id" end create_table "products", :force => true |t| t.string "name" t.integer "user_id" end
first should use build instead of create build instance of product, otherwise following line if @product.save
meaningless. code should this:
def create @product = current_user.products.build(params[:product]) # using build construct 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
Comments
Post a Comment