Search code examples
ruby-on-railsruby-on-rails-5

Rails - passing a variable to string interpolation


This is what's in my controller. I'm using devise and I'm trying to show take the user email and pass it into a where to find the specific family so I can display just the unique family controlled by the user.

I'm having an issue with the string interpolation. If I hard code the email into the query it works fine. But I want it to be dynamic. Thanks for the help!

home_controller.rb

  user_email = current_user.email
  @unique_family = Unit.where(:accountOwner => '#{user_email}')

Solution

  • For string interpolation you need to use double quotes "", like:

    name = 'Some name'
    puts "Hello #{name}"
    # => "Hello Some name"
    

    You see there name is defined within single quotes, but using the puts and interpolating the "Hello" string with the name variable, then is necessary to use double quotes.

    To make your where query you can try with:

    user_email = current_user.email
    @unique_family = Unit.where(:accountOwner => user_email)
    

    In such case isn't necessary to interpolate your user_email with "nothing" or trying to convert it to string, unless you want to make sure what's being passed will be an string, so you could do:

    @unique_family = Unit.where(:accountOwner => user_email.to_s)
    

    Or better:

    @unique_family = Unit.where('accountOwner = ?', user_email)
    

    That will bind the passed value for user_email to your query.