这是我的视图
<%= nested_form_for Post.new,html: {multipart: true},url: {action: :create} do |f| %>
<%= f.text_field :title,placeholder: 'title' %>
<%= f.fields_for :post_detail do |uploads| %>
<%= uploads.file_field :upload %>
<% end %>
<input type="submit" value="submit" />
这是我的post.rb
模型
has_many :post_details
accepts_nested_attributes_for :post_details
这是我的post_detail.rb
模型
belongs_to :post
has_attached_file :upload
这是我的 post_controller.rb
def create
@post = Post.new(post_params)
@post.post_details.build
if @post.save
flash[:success] = 'Post added successfully'
redirect_to root_path
else
flash[:error] = 'Post cannot add. Please try again after some time'
redirect_to action: :new
end
end
编辑 1
这是我可以看到的日志
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZjAnCeF2F1tkDVni96GcihdCd5JkyXHPaTIBjKoLq4s=", "post"=>{"title"=>"test","post_detail"=>{"upload"=>#<ActionDispatch::Http::UploadedFile:0xb2e8208 @tempfile=#<Tempfile:/tmp/RackMultipart20130911-3059-1ahxfek>, @original_filename="Ubuntu-Wallpaper-HD.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"post[post_detail][upload]\"; filename=\"Ubuntu-Wallpaper-HD.jpg\"\r\nContent-Type: image/jpeg\r\n">}}}
Unpermitted parameters: post_detail
Unpermitted parameters: post_detail
编辑 2
在rails 4中我像这样使用attr_accesible
private
def post_params
params.require(:post).permit(:title,post_details_attributes:[:upload_file_name,:upload_file_size,:upload_content_type])
end
编辑 3
我在 post_details 表中手动添加了 3 列
upload_file_name,upload_file_size and upload_file_content
仅为上述 3 个字段插入了 null 并且未上传图像。
编辑 4
如果我添加<%= f.fields_for :post_details do |uploads| %>
它本身不显示嵌套表单