Rails:要上传的文件不会从Form传递到控制器

时间:2016-03-04 00:14:59

标签: ruby-on-rails

这是表格。除了包含File的字段外,所有字段都被传递(并保存)。 我已经使用

检查过了
render plain: params[:article].inspect   method

给出这个(我为所有字段输入了值“n”):

{"country"=>"n", "region"=>"n", "town"=>"n", "street"=>"n", "company"=>"n", "title"=>"n", "content"=>"n"}

我在这里遗漏了多余的字段,以缩短表格:

<%= form_for(@article, html: { multipart: true }) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>       
          <%= f.label :country %>
          <%= f.text_field :country, :required => true, 
          placeholder: "enter country" %>
          </div>                  
      <%= f.label :content %>
      <%= f.text_field :content, :required => true, placeholder: "town..." %>
            </div>  
         </div>
     </div>         
  </div>       
<span class="picture">
   <%= form_for @article, html: { multipart: true } do |f| %>
     <%= f.text_field :title %>
     <%= fields_for :pictures do |ff| %>
     <%= ff.file_field :picture %>
   <% end %>
  <% end %> 
</div>

我也尝试过这里的轻微变化,但没有变化

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for

Controller的create方法如下:

def create
      @article = current_user.articles.build(article_params)
    if @article.save
      flash[:success] = "Article created!"
      redirect_to root_url
    else
      render 'articles/new'
    end
  end

并且是的,文章控制器中的新方法就像我在这里被同行指出的那样:

def new
    @article  = current_user.articles.build 
    @article.pictures.build
  end

文章模型

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :pictures
  accepts_nested_attributes_for :pictures, allow_destroy: true

图片模型

class Picture < ActiveRecord::Base
  belongs_to :article
 mount_uploader :picture, PictureUploader

end

1 个答案:

答案 0 :(得分:1)

将您的<%= fields_for :pictures do |ff| %>更改为<%= f.fields_for :pictures do |ff| %>