eastwood
eastwood

Reputation: 3

Assign associated objects by association name (as string) in Rails3

class Item < ActiveRecord::Base
    has_many :subitems
end

Class SubItem < ActiveRecord::Base
    belongs_to :item
end

I have an instance of Item and an array of subitems, but I only have the name of the association (as string). How to assign subitems to item?

item = Item.new
subitems = [] << SubItem.new << SubItem.new << SubItem.new

item.("subitems".do_some_magic) = subitems
item.save

Upvotes: 0

Views: 417

Answers (1)

Stobbej
Stobbej

Reputation: 1090

You could do this:

item.send("subitems") = subitems
item.save!

Upvotes: 1

Related Questions