将元素添加到rails has_many关系“动态”

时间:2015-03-17 01:04:53

标签: ruby-on-rails

拥有以下型号:

class Card < ActiveRecord:Base
  # ...whatever
  belongs_to :model
end

class Model < ActiveRecord:Base
  # attribute: rank
  has_many  :cards
end

考虑以下代码:

  mod = Model.new
  card = Card.first
  an_attribute = "rank"
  another_attribute = "cards"

  mod.send("#{an_attribute}=", 1) # this works fine, OK
  mod.cards << card      # this works fine as well, OK
  mod.send("#{another_attribute}<<", card) # this does not work, hence my question

最后一行代码返回错误undefined method 'cards<<'

所以我的问题是:如何通过变量访问card mod.cards关系时将cards元素附加到has_many,即通过存储名称变量中的关联?

1 个答案:

答案 0 :(得分:1)

mod.send("#{another_attribute}").push(card)