6

我正在尝试在 Rails 中创建产品页面。这包括添加多个图像。我有一种产品模型,一种用于照片和用户。我正在使用回形针 gem 上传照片。但我有两个问题。

  1. 我的文件输入不允许我选择多个图像
  2. 当我查看产品时没有图片显示,因为图片没有保存到数据库中

PS 我使用 HAML,我没有照片控制器。

产品控制器

class ProductsController < ApplicationController
    before_filter :current_user, only: [:create, :destory]
    before_filter :correct_user, only: :destory

  def new 
@product = Product.new
    @photo = Photo.new
    5.times { @product.photos.build }
  end

  def create

  @photo = current_user.photos.build(params[:photo])

  @product = current_user.products.build(params[:product])
    if @product.save
        render "show", :notice => "Sale created!"
    else
        render "new", :notice => "Somehting went wrong!"
    end
end

def show
@product = Product.find(params[:id]) 
end

创建产品页面

= form_for @product, :html => { :multipart => true } do |f|
  - if @product.errors.any?
    .error_messages
      %h2 Form is invalid
      %ul
        - for message in @product.errors.full_messages
          %li
            = message
  %p
    = f.label :name
    = f.text_field :name
  %p
    = fields_for :photos do |f_i|
      =f_i.file_field :image 

  %p.button
    = f.submit

产品型号

class Product < ActiveRecord::Base
  attr_accessible :description, :name, :price, :condition, :ship_method, :ship_price, :quantity, :photo
  has_many :photos, dependent: :destroy
  accepts_nested_attributes_for :photos
  belongs_to :user

照片模型

class Photo < ActiveRecord::Base
  attr_accessible :product_id

  belongs_to :product
  has_attached_file :image,
    :styles => {
      :thumb=> "100x100#",
      :small  => "300x300>",
      :large => "600x600>"
        }
end

用户模型

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation, :name

  attr_accessor :password
  has_many :products, dependent: :destroy
  has_many :photos,:through=>:products

显示产品页面

  %b seller
  = @product.user.name
  %br 
  - @product.photos.each do |photo|
    = image_tag photo.image.url
4

6 回答 6

3

您的用户模型未附加到照片,因此照片仅属于产品模型,因此您需要将用户模型更改为

 class User < ActiveRecord::Base
  has_many :products
  has_many :photos,:through=>:products


  end

然后你可以通过获取用户照片

 @photos =current_user.photos 

或者您可以轻松构建照片

@photo = current_user.photos.build(params[:photo])

同样在您的观点中,您需要代替 = f.file_field :photo, multiple: 'multiple'

利用

= fields_for :photos do |f_i|
    =f_i.file_field :image

试试看 。

这是有很多通过关联的简单方法

   class Document < ActiveRecord::Base
  has_many :sections
  has_many :paragraphs, :through => :sections
  end

 class Section < ActiveRecord::Base
 belongs_to :document
  has_many :paragraphs
end

class Paragraph < ActiveRecord::Base
 belongs_to :section
 end

您可以查看这些指南以获取更多信息

http://guides.rubyonrails.org/association_basics.html 你也需要把

 accepts_nested_attributes_for :photos

在您的产品模型中

有关嵌套表单的完整教程,您可以观看这些屏幕截图

http://railscasts.com/episodes/196-nested-model-form-revised

它不是免费的

如果您没有订阅 railscasts.com,您可以观看这些免费的屏幕投射

http://railscasts.com/episodes/196-nested-model-form-part-1

http://railscasts.com/episodes/197-nested-model-form-part-2

于 2013-05-21T09:01:20.860 回答
2

试试这个:

新产品页面

= form_for @product, :html => {:multipart => true} do |f|
  %p
    = f.label :description
    = f.text_field :description

  = f.fields_for :photo do |fp|
    = fp.file_field :image
    = fp.check_box :_destroy
    = fp.label :_destroy, "Remove Image" 

  %p.button
    = f.submit

产品控制器

def new
  @product = Product.new
  @product.photos.build
end

def create  
  @product = current_user.products.create(params[:product])
  # or
  # @product = current_user.products.build(params[:product])
  # @product.save
end

产品型号

class Product < ActiveRecord::Base
  attr_accessible :description, :name, :photo
  accepts_nested_attributes_for :photo, :reject_if => lambda { |p| p[:image].nil? }, :allow_destroy => true

  belongs_to :user
  has_many :photos, dependent: :destroy

  validates :user_id,      presence: true
  validates :photo,        presence: true
end

照片模型

class Photo < ActiveRecord::Base
  attr_accessible :image
  belongs_to :product
    validates_attachment :image, presence: true,
         content_type: { content_type: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'] },
         size: { less_than: 5.megabytes }
    has_attached_file :image, styles: { medium: "320x240>"}

end
于 2013-05-29T07:15:53.287 回答
1
  1. 如果您使用嵌套形式,则不需要单独创建每个对象。创建产品将创建嵌套照片。
  2. build方法只创建一个对象。它不会将对象保存到数据库。您应该调用object.save或使用create方法而不是build在您的创建操作中
于 2013-05-29T07:23:18.317 回答
1

您是否Resque用于后台作业,如果是,那么您需要使用rake resque:work QUEUE='*'.in rails 启动它通常Resque用于处理涉及邮件和图片上传的后台作业。或者下面的示例 product.html.erb 有部分照片上传带有回形针的产品配置了 Amazon S3。

产品.html.erb

<%= render :partial => 'photos' %>

_photos.html.erb 对于至少一张图片是强制性的

       <% if @product.photos[0].nil? %>
                <a href="javascript:void(0);" class="add-photos" >
                <img src="/assets/default/product-add-photos.png" alt="Add product photos"/>              
                 </a>   
        <% end %>
 <img src="<%= (@product.product_photos[0].nil? ? "" : @product.photos[0].image.url(:small)) %>" id="photos_1" class="product-photos-src <%=@product.photos[0].nil? ? 'dontdisplay' : ''%> "/>
于 2013-05-29T11:20:59.423 回答
0

我认为这里真正的问题是你想通过回形针在一个模型上附加多张照片。回形针每个模型只能附加 1 个文件,所以我建议你这样做:

1. create model Photo with paperclip migrations + has_attached_file
2. Product has_many :photos
3. (optional) make a function to return all image urls, otherwise just call the method in the view

   class Product 
     def get_pics
        photos.collect{|p| p.image.url}
     end
   end

还有一件好事,您现在可以在照片模型中包含 alt 文本和其他内容等元数据!

<% @product.photos.each do |photo| %>
  <%= image_tag photo.image.url, :alt => photo.alt_text %>
<% end %>
于 2013-05-21T09:42:54.367 回答
0

我也遇到了同样的问题。我在stackoverflow上问过,最后解决了自己和rails cast的帮助。

首先要改变的是: 你必须按照这个在模型端和控制器端实现嵌套属性:

http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

然后点击下面的链接,检查我对问题的回答,它包括嵌套表单应该遵循的 rails cast 链接:

您将看到 rails cast 2nd 链接动态地分隔您的每个字段字段,因为它无法单独分隔每组字段。但是在 rails-cast 中也缺乏身份唯一性算法的准确性。所以我增强以确保某些字段集与其他字段的唯一性。

jquery 只渲染一次,第二次它不会再次渲染,只显示前一个

于 2013-05-30T08:16:33.633 回答