Colibri
Colibri

Reputation: 1195

How to work with fields from a join table in many-to-many relationships?

I have the usual many-to-many relationship:

class Post < ApplicationRecord
  has_many :posts_and_images
  has_many :images, through: :posts_and_images
end

class PostsAndImage < ApplicationRecord
  belongs_to :post
  belongs_to :image
end

class Image < ApplicationRecord
  has_many :posts_and_images
  has_many :posts, through: :posts_and_images
end

I added a field to the posts_and_images table. And now I can't understand how I can work with this field.

For example, I added a description field to the posts_and_images table. That is, this field with a unique description for each image of each post.

I want to work with this field like this:

- @post.images.each do |image|
  / ...
  = content_tag :div, image.description

Tell me, please, how can I achieve this result?

Upvotes: 0

Views: 25

Answers (1)

max
max

Reputation: 101976

You want to start by naming the join model according to the conventions. PostsAndImage is just weird in every way.

class Post < ApplicationRecord
  has_many :post_images
  has_many :images, through: :post_images
end

class PostImage < ApplicationRecord
  belongs_to :post
  belongs_to :image
end

class Image < ApplicationRecord
  has_many :post_images
  has_many :posts, through: :post_images
end

But you could probaly come up with better names like attachment, media, etc.

Instead of iterating through images you want to iterate through post_images:

- @post.post_images.each do |post_image|
  = content_tag :div, post_image.description
  # you can get the image with post_image.image

Upvotes: 1

Related Questions