I have 3 models: Post, Comment, and Image
(I am using paperclip gem BTW)
What I am trying to achieve is that users can comment on post. Also, if they opt to comment images in the post, they could do so. The relationship looks like this:
For Post
class Post < ApplicationRecord
belongs_to :user
has_many :comments, :dependent => :destroy
end
For Comment
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
has_many :images, :dependent => :destroy
end
and for Image
class Image < ApplicationRecord
belongs_to :user
belongs_to :comment
end
The process is that for example, they would like to comment on a post, and would like to attach an image, they could do so by attaching an image to the comment. They could also attach multiple image in one comment.
However, I can't seem to know how to do that. Upon researching, I stumbled this post which upload multiple images in a gallery.
However, it is only two layer model (Gallery and Picture). He makes use of this code in his view and controller:
View
<%= file_field_tag "images[]", type: :file, multiple: true %>
controller
if params[:images]
params[:images].each { |image|
@market.pictures.create(image: image)
}
end
I get on how to do that. But it is different from what I'm trying to achieve. If you can help me, that would be great! Thanks in advance!
accepts_nested_attribues_foris what you're looking for. stackoverflow.com/questions/18535748/…