0

There are lots of stringify_keys questions here, but i can't find proper match to my problem, so i'll appreciate at least any example matching it.

I have three models named Song, Mixtape and MixtapeSong.

class Song < ActiveRecord::Base
  attr_accessible :duration, :name, :order

  belongs_to :album

  has_many :mixtape_songs
  has_many :mixtapes, :through => :mixtape_songs
end

class Mixtape < ActiveRecord::Base
  attr_accessible :description, :image, :name

  has_many :mixtape_songs
  has_many :songs, :through => :mixtape_songs
end

class MixtapeSong < ActiveRecord::Base
  attr_accessible :mixtape_id, :order, :song_id
  belongs_to :mixtape
  belongs_to :song
end

When i tried below commands through rails console, i succeed to add a record to mixtape_songs table with mixtape_id and song_id values but also with an 'order' NULL:

mtape = Mixtape.find(1)
song  = Song.find(3)
mtape.songs << song

Also executing an update_attributes was failed with 'Undefined method signify_keys' error.

params = [:mixtape_id => 1, :song_id => 3, :order => 2]
mts = MixtapeSong.find(1)
mts.update_attributes(params)

What i need to do is adding this association through Mixtape model with specifying an 'order' value or through MixtapeSong model without 'Undefined method signify_keys' error.

I guess the right way is adding through Mixtape model but i can't figure out how to set 'order'? Any help is appreciated.

4

1 回答 1

0

Fetching:

mtape = Mixtape.find(1)
songs_in_proper_order = mtape.songs.order(mixtape_songs: :created_at)

Swapping:

MixtapeSong.transaction do
    ms1 = MixtapeSong.find(1)
    ms2 = MixtapeSong.find(2)

    ms1.created_at, ms2.created_at = ms2.created_at, ms1.created_at

    ms1.save
    ms2.save
end
于 2012-05-20T19:48:46.600 回答