Ala*_*man 6 ruby ruby-on-rails paperclip ruby-on-rails-3
我正在尝试在rails中创建一个创建产品页面.这包括添加多个图像.我有一个产品模型,一个用于照片和用户.我正在使用paperclip gem进行照片上传.但我有两个问题.
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
Run Code Online (Sandbox Code Playgroud)
创建产品页面
= 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
Run Code Online (Sandbox Code Playgroud)
产品型号
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
Run Code Online (Sandbox Code Playgroud)
照片模型
class Photo < ActiveRecord::Base
attr_accessible :product_id
belongs_to :product
has_attached_file :image,
:styles => {
:thumb=> "100x100#",
:small => "300x300>",
:large => "600x600>"
}
end
Run Code Online (Sandbox Code Playgroud)
用户模型
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :name
attr_accessor :password
has_many :products, dependent: :destroy
has_many :photos,:through=>:products
Run Code Online (Sandbox Code Playgroud)
显示产品页面
%b seller
= @product.user.name
%br
- @product.photos.each do |photo|
= image_tag photo.image.url
Run Code Online (Sandbox Code Playgroud)
小智 1
您是否用于后台作业,如果是,那么您需要使用.in RailsResque
启动它,通常用于处理涉及邮件程序和图片上传的后台作业。或者下面的 Product.html.erb 示例,其中包含部分照片上传带回形针的产品配置了 Amazon S3。rake resque:work QUEUE='*'
Resque
产品.html.erb
<%= render :partial => 'photos' %>
Run Code Online (Sandbox Code Playgroud)
_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' : ''%> "/>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1953 次 |
最近记录: |