拥有以下型号:
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
,即通过存储名称变量中的关联?
答案 0 :(得分:1)
mod.send("#{another_attribute}").push(card)