首先,我不得不說我是新手,所以對於新手問題感到抱歉。 我有了很多 「圖片」使用繭寶石添加多個圖像
class Post < ActiveRecord::Base
has_many :pictures, :dependent => :destroy
accepts_nested_attributes_for :pictures, :allow_destroy => true, :reject_if => lambda { |t| t['pictures'].nil? }
belongs_to :user
monetize :price
validates :title, :brand, :model, :price, :year, presence: true
end
和我的圖片模式 「後」 模式:
class Picture < ActiveRecord::Base
belongs_to :post
has_attached_file :image,
:path => ":rails_root/public/images/:id/:filename",
:url => "/images/:id/:filename",
styles: { medium: "600x600>"}
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
validates :image, presence: true
end
我的創造是:
def create
@post = current_user.post.build(post_params)
respond_to do |format|
if @post.save
if params[:images]
params[:images].each { |image|
@post.pictures.create(image: image)
}
end
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
我有很強的參數是:
def post_params
params.require(:post).permit(:title, :decription, :brand, :model, :price, pictures_attributes: [ :image, :_destroy])
end
我的形式:
= simple_form_for @post, html: { multipart: true } do |f|
.form-group
= f.input :title, input_html: { class: 'form-control'}
.form-group
= f.input :brand, input_html: { class: 'form-control'}
.form-group
= f.input :model, input_html: { class: 'form-control'}
.form-group
= f.input :description, input_html: { class: 'form-control'}
.form-group
= f.input :year, input_html: { class: 'form-control'}
.form-group
= f.input :price, input_html: { class: 'form-control'}
.form-group
= f.simple_fields_for :pictures do |pic|
= render 'picture_fields', f: pic
.links
= link_to_add_association 'add pictures', f, :pictures, class: "btn btn-default"
= f.button :submit, class: "btn btn-primary"
和
.form-inline.clearfix
.nested-fields
= f.file_field :picture
= link_to_remove_association "delete", f
當我加熱提交按鈕,後保存,但不能重複扔在演出後的圖片。 我的代碼中有錯誤嗎?有沒有解決方案知道圖片是否保存?當我使用紅寶石控制檯@post = Post.last和@ post.pictures給我這個:
圖片加載(2.0ms)選擇「圖片」。*從「圖片」在哪裏「圖片」。「post_id」 =? [ 「POST_ID」,34] =>#