0

I have 2 models with a through relationship:

PortfolioItem
has_many :portfolio_item_images
has_many :images, :through => :portfolio_item_images

PortfolioItemImage
belongs_to :image
belongs_to :portfolio_item

I want to associate a portfolio item image to a portfolio item and also set the portfolio item image's position.

Right now I'm doing it like this:

i13 = PortfolioItem.create({:name => 'Portfolio Item 1'})
i13_img01 = Image.find_by_image_name('Portfolio_Item_Image.jpg')
i13.images << i13_img01
i13_portimg01 = i13.portfolio_item_images.find_by_image_id(i13_img01.id)
i13_portimg01.update_attributes(:position => 1)

This is rather convoluted as I'm setting the relationship, then finding the through record from my image id and then setting the position on the portfolio item image.

I have a feeling there's a much cleaner Ruby/Rails way of doing this with ActiveRecord. But I didn't find anything on Google. Each time I Google associations, it's usually the Rails Guide that pops up and I couldn't find the information in there.

Also, I don't have much control over the Image model.

Thank you for your time!

Update: The image was also previously created. So I can't create it through PortfolioItem and add the attribute then. Thanks!

Zhao Li
  • 4,936
  • 8
  • 33
  • 51

1 Answers1

0

I think this should fit your need :

i13 = PortfolioItem.create({:name => 'Portfolio Item 1'})
i13.portfolie_item_images.create(image: Image.find_by_image_name('Portfolio_Item_Image.jpg'),
                                 position: 1)
Adrien Coquio
  • 4,870
  • 2
  • 24
  • 37
  • Hi Adrian, thank you for the input. However,the image object was previously created. I'll edit my question to highlight this. Thanks again! – Zhao Li Nov 15 '12 at 20:53
  • I did not trying to create the image object, I'm still using `Image.find_by_image_name` like you did. – Adrien Coquio Nov 16 '12 at 06:54