Ala*_*man 6 ruby ruby-on-rails paperclip ruby-on-rails-3
我正在尝试在rails中创建一个创建产品页面.这包括添加多个图像和文本字段.我有一个产品型号和一个照片.我正在使用paperclip gem进行照片上传.但是当我查看产品页面时,我没有得到任何图片.照片未保存到数据库.
PS我使用HAML.
应用程序/视图/产品/ show.html.haml
%b Name
= @product.name
%br
%b Description
= @product.description
%br
- @product.photos.each do |photo|
= image_tag photo.image.url
Run Code Online (Sandbox Code Playgroud)
应用程序/控制器/ products_controller
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
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 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
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)
应用程序/产品/ new.html.haml
= form_for @product, :html => { :multipart => true } do |f|
%p
= fields_for :photos do |f_i|
=f_i.file_field :image
Run Code Online (Sandbox Code Playgroud)
小智 3
首先你的形式是错误的,q用于注册照片使用fields_for,然后你使用fields_for f.object.photos或使用Photo.new做| g |,您的关系模型中的其他错误 has_attached_file 是 has_many 照片,has_attached_file 回形针适合在要使用的模型中使用,而不是在与其他模型的关系中使用。希望这会有所帮助,现在要拥有一个带有多张照片的产品,我建议您使用 gem cocoon,我根据您的情况进行选择, https: //github.com/nathanvda/cocoon
| 归档时间: |
|
| 查看次数: |
2716 次 |
| 最近记录: |