我是Stackoverflow&铁轨。我有三种型号,用户,帖子,post_attachment(创建post_attachment脚手架(。我想做的是,每个帖子(帖子的标题,内容,图片(用户只能上传5张图片(我的意思是每个帖子(。我转介本文以实现多个图像,并基本遵循此代码。我还发现了这篇文章来验证Nested_attributes,但只有图片验证(Nested_attributes(无法正常工作。任何想法,将不胜感激。谢谢。
user.rb:
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
end
POST.RB:
class Post < ActiveRecord::Base
belongs_to :user
has_many :post_attachments
accepts_nested_attributes_for :post_attachments,allow_destroy: true, reject_if: :all_blank
end
POST_ATTACHMENT.RB:
class PostAttachment < ActiveRecord::Base
mount_uploader :picture,PictureUploader
belongs_to :post
end
POST_CONTROLLER.RB:
def new
@post = Post.new
@post_attachment = @post.post_attachments.build
end
def show
@post_attachments = @post.post_attachments.all
end
def create
@post = current_user.posts.build(post_params)
if @post.save
params[:post_attachments]['picture'].each do |a|
@post_attachment = @post.post_attachments.create!(:picture => a, :post_id => @post.id)
end
redirect_to @post, notice: "Post Saved"
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:title,:content,:user_id,post_attachments_attributes: [:id, :post_id, :picture, :_destroy])
end
您可以将条件放在create
和edit
方法之前,也可以将条件放在edit.html.erb
中。就像您想节省最多5张照片,可以使用
def create
@post = current_user.posts.build(post_params)
if @post.save
##@post_attachments = PostAttachment.find_by_post_id(@post.id) --> this can be use in edit
##if params[:post_attachments]['picture'].length+ @post_attachment.length <= 5
if params[:post_attachments]['picture'].length <= 5
params[:post_attachments]['picture'].each do |a|
@post_attachment = @post.post_attachments.create!(:picture => a, :post_id => @post.id)
end
elsif params[:post_attachments]['picture'].length > 5
flash[:error] = 'Your message'
redirect_to YOUR_PATH
return false
end
redirect_to @post, notice: "Post Saved"
else
if params[:post_attachments]['picture'].length > 5
@post.errors[:base] << "Maximuim 5 messages/pictures."
end
render 'new'
end
end
还可以在编辑帖子时查看中的查看。
<% if @post_attachments.length <= 5 %>
<%= f.file_field %>
<% end %>