【发布时间】:2012-05-20 19:03:01
【问题描述】:
这里有很多 stringify_keys 问题,但我找不到与我的问题合适的匹配项,所以我至少会感谢任何匹配它的示例。
我有三个模型,分别名为 Song、Mixtape 和 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
当我通过 rails 控制台尝试以下命令时,我成功地将一条记录添加到 mixtape_songs 表中,其中包含 mixtape_id 和 song_id 值,但“订单”为 NULL:
mtape = Mixtape.find(1)
song = Song.find(3)
mtape.songs << song
执行 update_attributes 也失败,出现“未定义的方法 signify_keys”错误。
params = [:mixtape_id => 1, :song_id => 3, :order => 2]
mts = MixtapeSong.find(1)
mts.update_attributes(params)
我需要做的是通过 Mixtape 模型添加此关联并指定“订单”值或通过 MixtapeSong 模型添加此关联,而不会出现“未定义方法 signify_keys”错误。
我想正确的方法是通过 Mixtape 模型添加,但我不知道如何设置“订单”?任何帮助表示赞赏。
【问题讨论】:
-
括号错误!使用卷曲的:
{:mixtape_id => 1, :song_id => 3, :order => 2} -
谢谢@jdoe,我更正了它并且它有效。有没有办法通过 Mixtape 或 Song 模型来做到这一点?或者因为我有一个额外的字段而不是相关字段,我是否必须使用 MixtapeSong 才能插入/更新“订单”val?
-
您是否需要按照“插入”它们的顺序为特定的 Mixtape 提取歌曲?
标签: ruby-on-rails ruby-on-rails-3 associations