Raoot
Raoot

Reputation: 1771

Rails 3.1 / Ruby - Nested loops?

I'm having some trouble with nested loops. Does anyone know a better way of doing this:

@product.tracks.each do |t|
    t.artists_tracks.each do |at|
        at.role = at.artist.role
        at.position = at.artist.position
        at.save
    end
end

I'm getting an undefined method role = error

Thanks in advance

Upvotes: 1

Views: 1594

Answers (2)

Alexandre Abreu
Alexandre Abreu

Reputation: 1417

@product.tracks.each do |track|
    track.artists_tracks.each do |at|
        at.role = track.artist.role
        at.position = track.artist.position
        at.save
    end
end

But yeah.. sure thing you need to review your models attrs

Upvotes: 1

tokland
tokland

Reputation: 67850

Some comments:

  • You should be able to write @product.artist_tracks provided you have a has_many :artist_tracks, :through => :artists.

  • at.role = at.artist.role. You are breaking the basic SQL rule of not having data duplicated, let the artist have the role.

Upvotes: 0

Related Questions