【问题标题】:Undefined method 'stringify_keys' error when using many to many association使用多对多关联时出现未定义的方法“stringify_keys”错误
【发布时间】: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 =&gt; 1, :song_id =&gt; 3, :order =&gt; 2}
  • 谢谢@jdoe,我更正了它并且它有效。有没有办法通过 Mixtape 或 Song 模型来做到这一点?或者因为我有一个额外的字段而不是相关字段,我是否必须使用 MixtapeSong 才能插入/更新“订单”val?
  • 您是否需要按照“插入”它们的顺序为特定的 Mixtape 提取歌曲?

标签: ruby-on-rails ruby-on-rails-3 associations


【解决方案1】:

获取:

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

交换:

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

【讨论】:

  • 没错,但如果我在创作歌曲后需要重新排序怎么办?
  • 这就是为什么我问你你的意图!你没有提到这种可能性:) 但无论如何,如果你想交换 2 首歌曲,只需交换他们 mixtape_songs 的:created_at。你需要通过:created_at而不是:id来订购歌曲。
  • 好的,使用:created_at 订购是不使用除关联字段外的额外字段的解决方案。我会试试这个,谢谢:)
  • 不是“覆盖”。它是由 Rails 为您创建的,应该保持这种状态。也许这就是你的意思,但值得注意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 2013-02-05
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
相关资源
最近更新 更多