A
A
Anton Misyagin2015-04-29 22:23:00
Ruby on Rails
Anton Misyagin, 2015-04-29 22:23:00

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

Somewhere in the controller:
@item = Item.new
@item.subitem = Subitem.new

Now @item.subitemnot 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

It doesn't work @item.subitemit's nil. Tried through attributes, but found out by experiment that subitem for Item is a method.
In general, I need the code to not have a hard registration of the name of the method, but to refer to it through its name. It is necessary that the result was like with a hard registration. Can you help?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Misyagin, 2015-04-29
@sunnmas

@item = Item.new
@item.send(:subitem.to_s+'=', Subitem.new)

V
Viktor Vsk, 2015-04-29
@viktorvsk

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 question

Ask a Question

731 491 924 answers to any question