Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Rails: Creating a method to save to a database column dynamically

User.rb

   def save_to_db(column_name)
      column = (column_name + "_data")
      self.column = "blah blah blah"
   end

e.g.

if I called save_to_db("stripe"), my intention would be to save "blah blah blah" to the user.stripe_data column.

But I'm having trouble converting the string into a method that I can call on self to save to DB.

Upvotes: 1

Views: 19

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176402

Assuming I understood your request correctly, you can use the []= method

def save_to_db(column_name)
  self["#{column_name}_data"] = "blah blah blah"
end

or use send.

def save_to_db(column_name)
  self.send("#{column_name}_data=", "blah blah blah")
end

Another approach that bypasses setters is to use write_attribute directly. But you can use this method only inside the model itself.

def save_to_db(column_name)
  self.write_attribute("#{column_name}_data", "blah blah blah")
end

Upvotes: 1

Related Questions