0

これが私のフォームです

<%= 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_accessibleを使用しました

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| %>と、ネストされたフォーム自体が表示されません

4

2 に答える 2

0

これを試して、

private
  def post_params
    params.require(:post).permit(:title,post_details_attributes: [:id, :upload])
  end
于 2013-09-12T05:11:50.893 に答える