1

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!

2
  • accepts_nested_attribues_for is what you're looking for. stackoverflow.com/questions/18535748/… Commented Jan 6, 2018 at 22:55
  • What does your controller look like? Is it currently the same as the example you cited? If you can get it to work with one image, you might only need a small change to support multiple images. Commented Jan 7, 2018 at 1:11

1 Answer 1

1

there may be different approach to upload but i would like to prefer this approach here with nested attributes and cocoon gem here you can get an example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.