Rails - 无法将另一个模型的照片添加为索引

时间:2013-06-04 17:44:04

标签: ruby-on-rails ruby ruby-on-rails-3

我正在尝试创建一个允许用户上传照片的创建产品页面。所以产品有很多照片。我设置了这个,但是当添加照片时,它应该在列中包含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

schema.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

1 个答案:

答案 0 :(得分: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