【发布时间】:2015-12-17 23:27:58
【问题描述】:
首先,我不得不说我是 Rails 新手,很抱歉提出新手问题。 我有一个包含许多“图片”的“帖子”模型
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
当我加热提交按钮时,帖子被保存但无法迭代将帖子图片扔到节目中。 我的代码有错误吗?有没有办法知道图片是否保存?当我使用 ruby 控制台时,@post = Post.last 和 @post.pictures 给了我这个:
图片加载 (2.0ms) SELECT "pictures".* FROM "pictures" WHERE "pictures"."post_id" = ? [[“post_id”,34]] => #
【问题讨论】:
标签: ruby-on-rails nested-forms cocoon-gem