0

我正在尝试创建一个允许用户上传照片的产品页面。所以产品有_很多照片。我已经设置好了,但是当添加照片时,它应该在一列中有 product_id,但是当它保存到我的数据库时,product_id 列是空白的。

产品控制器

  def create

  @product = current_user.products.build(params[:product])
  @photo = current_user.photos.new(params[:photo])

    if @product.valid? && @photo.valid?
      @product.save
      @photo.save
      @photo.product_id = @product.id
      render "show", :notice => "Sale created!"
    else
      render "new", :notice => "Somehting went wrong!"
    end
end

新产品页面(HAML)

%h1 
  create item
= form_for @product,:url => products_path, :html => { :multipart => true } do |f|         
  %p
    = f.label :name
    = f.text_field :name
  %p
    = f.label :description
    = f.text_field :description
  %p
    = fields_for :photo, :html => {:multipart => true} do |fp|
      =fp.file_field :image  

  %p.button
    = f.submit

架构.rb

  create_table "products", :force => true do |t|
    t.string   "name"
    t.text     "description"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
    t.integer  "user_id"
  end

  create_table "photos", :force => true do |t|
    t.integer  "product_id"
    t.datetime "created_at",         :null => false
    t.datetime "updated_at",         :null => false
    t.string   "image_file_name"
    t.string   "image_content_type"
    t.integer  "image_file_size"
  end
4

1 回答 1

1

这仅仅是保存第@photo一个,然后在保存后设置它的结果product_id,当然这永远不会在数据库中更新。只需反转操作即可。

if @product.valid? && @photo.valid?
  # Recommended to test for success saving the product
  if @product.save
    # Set the product_id before saving
    @photo.product_id = @product.id
    # Then save the photo
    @photo.save
    render "show", :notice => "Sale created!"
  end
else
  render "new", :notice => "Somehting went wrong!"
end
于 2013-06-04T17:55:18.303 回答