Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all childs active-storage attachments in rails?

let's say there are 2 models.

user model:

has_many :posts

post model:

belongs_to :user

has_many_attached :files, dependent: :destroy

what I want is simply all files of the user. something like:

has _may :post_files , through: posts, class_name: "XXX"

or any other way which can give me all the files of the user.

so I want all files of all posts which belong to the user. like user.post_files

like image 539
Navid Farjad Avatar asked Sep 04 '19 14:09

Navid Farjad


2 Answers

thank you all for your answers. I found the solution.

has_many_attached :files actually sets two has_many relationships:

has_many :files_attachments and has_many :files_blobs

So in user.rb (parent model) we can simply have:

has_many :files_attachments, through: :posts

and in this way, you can have user.files_attachments to get all files of posts for one user.

like image 167
Navid Farjad Avatar answered Sep 18 '22 22:09

Navid Farjad


Here is how the structure should be

user.rb <-- User model

has_many :posts

post.rb <-- Post model

belongs_to :user 
has_many_attached :files

this way you can do

Post.post_files

or

Post.with_attached_files.find(params[:id])

In conclusion.

The attachments belong to the Post, not to the User, so there is no need to make any call to User model

like image 45
Diego Velez Avatar answered Sep 20 '22 22:09

Diego Velez