Answer the question
In order to leave comments, you need to log in
Dynamically assign a value to a model attribute via its name?
Couldn't articulate the title of the question clearly. Let me explain what is needed.
Models:
class Item < ActiveRecord::Base
has_one: subitem
end
class Subitem < ActiveRecord::Base
belongs_to: item
end
@item = Item.new
@item.subitem = Subitem.new
@item.subitem
not nil. Everything works great here. But suddenly there was a need to access subitem through a character or a string. I rewrite that code:@item = Item.new
@item.methods(:subitem) = Subitem.new
@item.subitem
it's nil. Tried through attributes, but found out by experiment that subitem for Item is a method. Answer the question
In order to leave comments, you need to log in
It is not entirely clear what is needed and for what purposes.
there's a
send(:sym) method (instead of method)
Or maybe you need to do:
item = Item.new
attr = :subitem
item.send("build_#{attr}".to_sym)
item.send(attr)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question