has_many关系的嵌套属性

时间:2015-09-10 05:28:30

标签: ruby-on-rails paperclip nested-attributes has-many

我的模特

class History < ActiveRecord::Base
  belongs_to :projects_lkp
  has_many :pictures
  accepts_nested_attributes_for :pictures
end

class Picture < ActiveRecord::Base
  belongs_to :history
  validates_presence_of :pics
end

history/new.html.erb

<%= form_for(:history, :url => {:action => 'create'}) do |d| %>
  <%= render(:partial =>"form",:locals => {:d => d}) %>
<% end %>

history/_form.html.erb

<%= d.fields_for :pictures do |dd| %>   
  <div class="row form-group"></div>
    <div><class='col-md-5 form-label'>Photo</div>
    <%= dd.file_field :pic, multiple: true, :class => 'col-md-15' %>
  </div>
<% end %>     

history_controller

def create
  @history = History.new(history_params)
  @history.projects_lkp_id = params[:projects_lkps_id]
  respond_to do |format|
    if @history.save
      format.html{ redirect_to histories_path(id: @history.id), notice:"History added" }
    else
      @history = History.where(item: @history.item).all
      format.html { render 'index' }
    end
  end
end

def history_params
  params.require(:history).permit(:history,:date,:pic)
end

但是当我尝试提交表单时,它表示未经许可的参数:图片

参数传递是:

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"xE8d/mD1pXh/2AIKrZlRoL552iEBVZ7jkzLJB1kNZyE=", "history"=>{"history"=>" jhafjkaalkds", "date"=>"20/10/2014", "pictures"=>{"pic"=>[#<ActionDispatch::Http::UploadedFile:0x0000000143d1f8 @tempfile=#<Tempfile:/tmp/RackMultipart20150910-2753-1ml2hmf>, @original_filename="Firefox_wallpaper.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"history[pictures][pic][]\"; filename=\"Firefox_wallpaper.png\"\r\nContent-Type: image/png\r\n">]}}, "projects_lkps_id"=>"", "commit"=>"Submit"}

未经许可的参数:图片

这里:pic是使用paperclip gem

创建的附件字段

2 个答案:

答案 0 :(得分:1)

试试这个:

def history_params
  params.require(:history).permit(:history, :date, pictures_attributes: [:pic])
end

我能看到的另一个问题是你的表格。它应该是:

<%= form_for(:history, :url => {:action => 'create'}, multipart: true) do |d| %>
  <%= render(:partial =>"form",:locals => {:d => d}) %>
  <%= d.fields_for :pictures do |dd| %>   
    <div class="row form-group"></div>
    <div><class='col-md-5 form-label'>Photo</div>
      <%= dd.file_field :pic, multiple: true, :class => 'col-md-15' %>
    </div>
  <% end %>
<% end %>

参数应采用以下形式:

"history" => { ... , "photos_attributes" => { "0" => { ... } } }

答案 1 :(得分:0)

我找到了答案:)

历史记录控制器

 def new
    @histories = History.new
   @histories.pictures.build
 end  

历史/新

      <%= form_for(@histories, :url => {:action => 'create'}, html: {multipart:true})  do |d| %>
      <%= render(:partial =>"form",:locals => {:d => d}) %>
      <% end %>

它有效:)