【发布时间】:2017-04-16 08:40:24
【问题描述】:
我是 stackoverflow 和 Rails 的新手。我有三个模型,User、Post、post_attachment(创建 post_attachment 脚手架)。 我想做的是,每个帖子(帖子标题,内容,图片)用户最多只能上传5张图片(我的意思是每个帖子)。我参考了这个article来实现多张图片和基本上遵循这个代码。我还发现这个article 来验证nested_attributes 但只有图片验证(nested_attributes)不起作用。任何想法,将不胜感激。谢谢。
用户.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
【问题讨论】:
标签: validation ruby-on-rails-4 limit carrierwave nested-attributes