fullybaked
fullybaked

Reputation: 4127

How do I dynamically access ActiveRecord instance attributes?

Basically I'm doing a find an replace over a set of text with data from the db, but the replacement tags are generated by the user and can be any of a huge selection.

How do you access a model record when the field name is in a variable

Normal access is

var = model.field_name

But in my code, I would like to do something like this

replacement_tags.each do |tag|
  content = content.gsub(/tag/, model.|access attribute with same name as tag|
end

so if tags were firstname, lastname the block would run gsub for model.firstname and model.lastname consecutively.

I don't mind if I'm going about this the wrong way, as long as there is some way to achieve these results

Upvotes: 0

Views: 926

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

When you're calling instance methods in Ruby, you are not calling anything, you're sending messages to the receiver.

user.first_name can be read as "send message to this user object that asks it to return its first name"

Equipped with this knowledge and this documentation, you can easily write your code as

replacement_tags.each do |tag|
  content = content.gsub(/tag/, model.send(tag.to_sym))
end

Upvotes: 4

Related Questions