导入导出xml

controller中

  def export_steps
    s = @part.steps.where('program_id in (?)', Program.checkable.map(&:id))
    send_data s.to_xml(:only => [:position, :program_id, :name, :minute, :description]), :filename => "#{@part.chart.name}.xml"
  end

  def import_steps
    if xml_file = params[:part][:xml_file]
      attrs = Hash.from_xml xml_file.read
      @part.steps << attrs.values.first.inject([]) {|a, s| a << Step.new(s) }
      flash[:notice] = I18n.t("flash.upload.success")
    else
      flash[:error] = I18n.t("flash.upload.no_file")
    end
    redirect_to :back
  rescue err # rescue any other format problem
    redirect_to :back, :error => I18n.t("flash.upload.fail")
  end
 

 

views中

<% if params[:part_id] -%>
  <% part = Part.find(params[:part_id]) -%>

  <div id='dialog'>
    <%= semantic_form_for(part, :method => 'post', :url => import_steps_part_path(part)) do |f| %>
      <%= f.inputs do -%>
        <%= f.input :xml_file, :as => :file %>
      <% end %>
      <%= f.actions do -%>
        <%= f.submit '上传' %>
      <% end %>
    <% end %>
  </div>

<% end -%>


<li><%= link_to '工艺模板导出', export_steps_part_path(@steps.first.part) if @steps.first.part %></li>
<li><a href='#' id='show-dialog'>工艺模板导入</a></li>
 

js.coffee中

  $('#show-dialog').click( ->
    $('#dialog').dialog({
      title: '上传模板文件',
      width: '400px'
    })
    return false
  )
 

route中

  resources :parts do
    collection do
      get 'outsource'
    end

    member do
      get 'export_steps'
      post 'import_steps'
    end
  end

你可能感兴趣的:(xml,Rails)