In Rails has_one
relationship, if the association name is stored in a string, how to build the child object whose name is saved in a string?
For example, a customer
has_one address
:
class Customer < ActiveRecord::Base
has_one :address
end
We can do:
customer = Customer.new
address = customer.build_address
If the association is saved in a variable name @association
, How can we create address
with the variable @association
?:
@association = 'address'
customer = Customer.new
address = customer.build_{@association} #code does not work.
We tried customer.build_"#{@association}" & 'customer.build_#{@association}
and none of them worked.
You want to do meta-programming, ie here, calling a method whose name is contained in a variable.
The Ruby method you need to use is send :
customer.send("build_#{association_name}")
You can only use the #{...}
syntax in double quoted strings ".."
OR regex /../
Note that send also work with symbols, and you can supply parameters after the first one. Remember that =, [], !, ?
are also part of the method name.
method= 'name=',
new_name= "hello"
@your_object.send(method, new_name)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.