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