Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
How use varaible as column name in Rails 6

I would make this code shorter.

def foo type, user
  if type == "foo"
    user.foo
  elsif type == "bar"
    user.bar
  end
end

user is ActiveRecord object

type is string "foo" or "bar"

If I have more types then I need to make more elsif. It's possible to make it shorter (without using the model method or any other additional code) using type variable as a column name? Something like:

user.{type} # ???
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You may use public_send to achieve this:

user.public_send(type)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!