我正在尝试在Rails中创建产品页面。这包括添加多个图像和文本字段。我有一个用于产品的模型和一个用于照片的模型。我使用paperclip gem进行照片上传。但是当我查看产品页面时,没有图片显示。照片没有保存到数据库。
附注:我使用HAML。
app/views/products/show.html.haml
附注:我使用HAML。
app/views/products/show.html.haml
%b Name
= @product.name
%br
%b Description
= @product.description
%br
- @product.photos.each do |photo|
= image_tag photo.image.url
应用程序/控制器/产品控制器
class ProductsController < ApplicationController
before_filter :require_login
before_filter :current_user, only: [:create, :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
app/models/photo
class Photo < ActiveRecord::Base
attr_accessible :product_id
belongs_to :product
has_attached_file :image,
:styles => {
:thumb=> "100x100#",
:small => "300x300>",
:large => "600x600>"
}
end
应用/模型/产品
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
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
app/products/new.html.haml
= form_for @product, :html => { :multipart => true } do |f|
%p
= fields_for :photos do |f_i|
=f_i.file_field :image