【问题标题】:nested attributes upload multiple photos in ror with paperclip嵌套属性使用回形针在 ror 中上传多张照片
【发布时间】:2013-02-28 11:23:32
【问题描述】:

我尝试上传照片,但似乎不起作用。 很多照片

在视图中>建筑>_form

<%= form_for(@building, :html=>{:multipart => true}) do |f| %>
  <% if @building.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@building.errors.count, "error") %> prohibited this building from being saved:</h2>

      <ul>
      <% @building.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :status %><br />
    <%= f.select :status, Building::STATUS, :prompt=>'Select status of the building' %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description, :rows => 10 %>
  </div>
  <div class="field">
    <%= f.label :location %><br />
    <%= f.text_field :location %>
  </div>
  <div class="field">
    <%= f.label :price %><br />
    <%= f.text_field :price %>
  </div>
  <div class="field">
    <h3>Tasks</h3>
  <% f.fields_for :tasks do |task_form| -%>
    <%= render :partial => 'task', :locals => { :form => task_form } %>
  <% end -%>


  <%= add_photo(f) %>

   <%= f.file_field :foto%>

      </div>

      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>

在视图中>建筑>_task

    <div class="task">
      <p>
        <%= form.label :name %>
        <%= form.text_field :name, :size => 15 %>
        <%= remove_task_link( form ) %>
      </p>
    </div>

in helpers>building_helpers

module BuildingsHelper

def add_photo(form_builder)
  link_to_function "add", :id  => "add_photo" do |page|
  form_builder.fields_for :tasks, Task.new, :child_index => 'NEW_RECORD' do |f|
        html = render(:partial => 'task', :locals => { :form => f })
        page << "$('tasks').insert({ bottom: '#{escape_javascript(html)}'.replace(/NEW_RECORD/g, new Date().getTime()) });"
       end
  end
end

   def remove_task_link(form_builder)
    if form_builder.object.new_record?
      # If the task is a new record, we can just remove the div from the dom
      link_to_function("remove", "$(this).up('.task').remove();");
    else
      # However if it's a "real" record it has to be deleted from the database,
      # for this reason the new fields_for, accept_nested_attributes helpers give us _delete,
      # a virtual attribute that tells rails to delete the child record.
      form_builder.hidden_field(:_delete) +
      link_to_function("remove", "$(this).up('.task').hide(); $(this).previous().value = '1'")
    end
  end
end

在控制器>建筑物中

 def new
    @building = Building.new
    2.times { @building.tasks.build }
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @building }
    end
  end

  # GET /buildings/1/edit
  def edit
    @building = Building.find(params[:id])
    2.times { @building.tasks.build }
  end

在视图中>布局>应用程序

<!DOCTYPE html>
<html>
<head>
  <title>Welcome to koshbay</title>
  <%= stylesheet_link_tag :all %>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>

  <%= csrf_meta_tags %>
</head>

模型>任务

class Task < ActiveRecord::Base
  attr_accessible :building_id, :name 
  belongs_to :project
has_attached_file :foto, :styles => { :medium => "300x300>",
                      :thumb => "100x100>" , 
                     :default_url => "/images/:style/missing.png"}

end

模型>建筑

class Building < ActiveRecord::Base
  attr_accessible :description, :price, :status, :title ,:location, `:foto`

  has_many :tasks, :dependent => :destroy
  # This is new!
  accepts_nested_attributes_for :tasks, :allow_destroy => true
 end

更新 1 个数据库表

db>create_task

class CreateTasks < ActiveRecord::Migration
  def change
    create_table :tasks do |t|
      t.string :name
      t.integer :building_id

      t.timestamps
    end
  end
end

db> create_buildings

class CreateBuildings < ActiveRecord::Migration
  def change
    create_table :buildings do |t|
      t.string :title
      t.string :location     
      t.string :status
      t.text :description
      t.decimal :price, :precision=>8, :scale => 2

      t.timestamps
    end
  end
end

更新 2

问题出在 _task.html.erb

更新 3

我已经运行 rails g 回形针建筑照片

现在在数据库中我有

class AddAttachmentFotoToBuildings < ActiveRecord::Migration
  def self.up
    change_table :buildings do |t|
      t.has_attached_file :foto
    end
  end

  def self.down
    drop_attached_file :buildings, :foto
  end
end

我正在使用这个例子 'http://railsforum.com/viewtopic.php?id=28447'

我没有收到任何错误,我看不到任何我可以上传照片的东西。当我按下添加按钮时没有做任何事情。

有什么想法吗?

【问题讨论】:

  • 要在 Rails 中执行此操作(因为我实际上不知道您的代码代表什么),您必须添加回形针 gem:github.com/thoughtbot/paperclip 按照文档安装 imageMagick,添加Paperclip.options 行...添加验证,更新视图以上传它,并始终记得在安装新 gem 后重新启动服务器(也不要忘记运行 bundle install)。
  • github.com/kosh8884/projectproperties.git 可以添加我有用户名并通过的建筑物:kosh,kosh4ever
  • 是的,我稍后再看

标签: ruby-on-rails upload paperclip nested-forms nested-attributes


【解决方案1】:

您可以在此处查看您的项目:

https://github.com/DamirSvrtan/For-mario

你可以从那里克隆它。无论如何,为您提供详细信息:

1.您没有将此行添加到您的config/environments/development.rb:

Paperclip.options[:command_path] = "/usr/local/bin/"

你可以看到我把那行放在那里,它实际上是"/usr/bin"

运行 which convert 命令,得到什么,只需从中剥离最后一个 '/convert' 并将其放入 development.rb 文件中。

2.您的建筑模型中有 foto 属性,但您的任务模型中有 has_attached。我也解决了这个问题。我还更改了您的视图并删除了嵌套属性来处理照片,而是制作了建筑形式来处理它。 我不小心删除了表单中的嵌套属性部分,所以把它拿回来,我想是两行。

3.由于某种原因,您的代码无法与 has_attachment 的“样式”部分一起使用。我真的不知道为什么会这样,因为到目前为止我的所有人都可以完美地使用它。 我试图修复它,但我找不到解决方案。其他一些人在 stackoverflow 上也有同样的问题,也许是一些 ruby​​-rails 版本的东西。我的脑海里没有别的东西。如果您没有找到解决方案,您仍然可以“呼吸”它,但是,也许在这里再次询问某人为什么会发生这种情况。

4.我把回形针宝石改成:

gem "paperclip", "~> 3.0"

5.希望您能理解我所做的所有更改。你可以接受或不接受代码,你的愿望。

【讨论】:

  • 感谢修复。但问题是我不希望它只用于 1 张照片放很多照片...对于一个我已经完成但对于许多照片来说是问题..这就是我制作任务和嵌套属性的原因..有什么想法吗?跨度>
  • 对于您要放入的每张照片,您都需要在餐桌建筑中添加额外的列。或制作一个额外的表格并将其与建筑物表格相关联。
  • 也许你可以尝试一下,我从来没有使用过嵌套属性。我忽略了nested_attributes 部分,但你可以在问题中提到它!下次让你的问题更清楚
  • 在我使用的示例中,我已经发布了许多照片的链接......
  • 至少这次你给了我一票哈哈。您将不得不使用嵌套属性来执行此操作。使用回滚删除您的最后一次迁移,它将从您的数据库中删除 foto 属性。将其添加到 Task 表中。实际上,请正常命名您的表格。也许像BuildingPhoto。请参阅此处的教程:railscasts.com/episodes/196-nested-model-form-part-1 现在您已经设置了整个回形针 gem,您只需要找出嵌套形式。记得迁移所有东西,不要把styleshas_attached放在一起。
【解决方案2】:

好的,这就是我使用嵌套属性所做的工作。 为此,您需要 2 插入 1)回形针 2)imagemagick

在 gemfile 中添加行

宝石'回形针'

然后在 cmd 中运行:bundle install

然后运行 ​​gem install rmagick //

一步一步

** p.s.:建筑是一个(建筑)与(许多)照片的关系**

第 1 步:我使用命令创建一个表:rails g model buildingphoto building_id:integer

分贝

class CreateBuildingPhotos < ActiveRecord::Migration
  def change
    create_table :building_photos do |t|
      t.integer :building_id


      t.timestamps
    end
  end
end

第 2 步:commant>rails g 回形针 buildingphoto photo

分贝

class AddAttachmentPhotoToBuildingPhotos < ActiveRecord::Migration
  def self.up
    change_table :building_photos do |t|
      t.has_attached_file :photo
    end
  end

  def self.down
    drop_attached_file :building_photos, :photo
  end
end

当完成第 2 步时运行:rake db:migrate

在模型中>建筑照片

class BuildingPhoto < ActiveRecord::Base
  attr_accessible :building_id , :photo
  belongs_to :building

    has_many :photo

    has_attached_file :photo

end

在模型>建筑中

class Building < ActiveRecord::Base
  attr_accessible :building_photos_attributes

  has_many :building_photos, :dependent => :destroy
  accepts_nested_attributes_for :building_photos
end

在控制器中>建筑控制器

def new
    @building = Building.new

    4.times { @building.building_photos.build }
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @building }
    end
  end

在视图中>建筑>_buildingphoto.html.erb // 我创建它

 <%= f.label :photo %><br />
    <%= f.file_field :photo %>

in views>building>_form.html.erb // 我添加了这一行

<div class="field">
   <%= f.fields_for :building_photos do |builder| %>
    <%= render "buildingphoto", :f => builder %>
  <% end %>
  </div>

in config>environments>development.rb // 告诉 Paperclip 在哪里可以找到您的 ImageMagick 安装(并非总是需要)

Paperclip.options[:command_path] = "/usr/bin/"

查看您上传的照片

<% building.building_photos.each do |photo| %>
        <%= link_to (image_tag (photo.photo.url)), building %>
        <% end %>

【讨论】:

    猜你喜欢
    • 2011-01-08
    • 2013-05-06
    • 1970-01-01
    • 2013-05-29
    • 2013-08-06
    • 2016-09-01
    • 1970-01-01
    • 2014-03-19
    • 2015-05-09
    相关资源
    最近更新 更多