ฉันยังใหม่กับ stackoverflow & Rails ฉันมีสามรุ่น User, Post, post_attachment(สร้าง post_attachment scaffold) สิ่งที่ฉันต้องการทำคือ ผู้ใช้ทุกโพสต์ (ชื่อโพสต์ เนื้อหา รูปภาพ) สามารถอัปโหลดได้สูงสุด 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