saya baru mengenal stackoverflow & Rails. Saya memiliki tiga model, Pengguna, Posting, post_attachment (Buat perancah post_attachment). Yang ingin saya lakukan adalah, setiap postingan (Judul postingan, Konten, Gambar) pengguna hanya dapat mengunggah maksimal 5 gambar (maksud saya setiap postingan). Saya merujuk article untuk mendapatkan banyak gambar dan pada dasarnya mengikuti kode ini. Saya juga menemukan artikel ini untuk memvalidasi nested_attributes tetapi hanya validasi gambar (nested_attributes) yang valid tidak bekerja. Setiap ide akan dihargai. Terima kasih.
Pengguna.rb:
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
end
Postingan.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