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!